简体   繁体   English

我在做什么错?.js while循环

[英]What am I doing wrong?.js while loop

How can I get 1 to 10 to show by fixing this code?? 修复此代码后如何显示1到10?

<script type="text/javascript"> 
    var count = 0; 
    var numbers = new Array(10);
    while (count <=10) { 
        numbers[count] = count;
        ++count;
    }
    count = 0;
    while (count <=10) {
        document.write(numbers[count] + 1 + "<br />");
        +count();
    }
</script> 

i am new to this, any help would be much appreciated 我是新来的,任何帮助将不胜感激

The main problem is this line: 主要问题是以下行:

+count();

This is a syntax error since you don't have a function called count , so execution simply stops as soon as it reaches that line. 这是一个语法错误,因为您没有名为count的函数,因此只要到达该行就立即停止执行。 Replace it with: 替换为:

++count;

(As done in the previous while loop.) (如上一个while循环中所做的那样。)

The second problem is that your loops are running from 0 to 10 inclusive , so you end up with 11 iterations. 第二个问题是您的循环从0到10( 0和10)运行,因此最终将进行11次迭代。 Change <= 10 to < 10 . <= 10更改为< 10

Having said that, the whole thing seems a bit pointless. 话虽如此,整个事情似乎毫无意义。 You create an array where item 0 holds the value 0, item 1 holds the value 1, etc., and then you print those values out? 您创建一个数组,其中第0项的值为0,第1项的值为1,依此类推,然后将这些值打印出来? Why bother with the array at all? 为什么要麻烦数组呢? There's no point looking up the item at any particular array index if you already know in advance the value will be the same as the index. 如果您已经事先知道该值将与索引相同,那么在任何特定的数组索引处查找项目都是没有意义的。

If all you want is to display the numbers 1 through 10 then this will work: 如果您只想显示数字1到10,那么它将起作用:

for (var i=1; i <= 10; i++)
   document.write(i + "<br />");

this will suffice: 这样就足够了:

var count = 0;
while (count <=9) {
    document.write(numbers[count] + 1 + "<br />");
    count++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM