提示变量未定义



这里我有一个简短的脚本,它将提示用户输入消息和数字值,然后重复该消息给定的次数。我继续收到消息变量的undefined。

<!doctype html>
<html lang="en">
<head>
<title>4</title>
</head>
<body>
<p id="change"> Launch this script</p>
<script type="text/javascript">   
    var x;
    var text = "";
    var message = prompt("Enter message here", "Leave a message");
    text == message;
    var number = parseInt(prompt("Enter a Value"));

    for (x=0; x<number; x++)
    {
        text += message.length[x] + "<br>";  
    }
    document.getElementById('change').innerHTML = text;
</script>
<br />
</body>
</html>

我假设你有两个问题:

  1. 这一行实际上什么也没做

    text == message;
    

    因为您使用了相等操作符(==)而不是赋值操作符(=),所以它相当于写

    false;
    
  2. for循环中有一行语法无效

    message.length[x]
    

    这应该给你错误,因为你试图索引([])到字符串的length属性,这是一个整数,而不是一个数组。这种语法只能用于对象和数组。根据您的需求,您应该附加message变量本身。

因此,考虑到所有这些,以下是我对修复代码的看法(在注释中更正并解释):
<script type="text/javascript">   
    // Don't need x here
    // Get your message, good
    var message = prompt("Enter message here", "Leave a message");
    // Set up an empty string variable to collect your concatenations. If you
    // set it to message right away, an input of 0 will actually produce
    // one line to be output, which is not 0!
    var text = '';
    // This is ok, but add a radix for good practice (it says this is
    // a base-10 value)
    var number = parseInt(prompt("Enter a Value"), 10);
    // You simply want to copy message number times, so just 
    // keep appending it to your text with a separator
    for (var x = 0; x < number; x++) { // Define x here ("var")
        text += message + "<br>";  
    }
    // Set the string
    document.getElementById('change').innerHTML = text;
</script>

jsFiddle演示

最新更新