[英]How do I get a sum of these numbers in array?
I want to use for
.我想
for
. There are two things, one, the console.log doesn't work inside the for statement.有两件事,一是console.log 在for 语句中不起作用。 Second, it is not summing up.
第二,不总结。 code below:
代码如下:
var numbers = [1,2,3,4];
var total = 0;
for (var i= 0; numbers.length < i; i++){
total += numbers[i];
// console.log(total); doesn't work
}
// console.log(total); gives 0
Change condition in for
should be i < numbers.length
not numbers.length < i
for
变化条件应该是i < numbers.length
而不是numbers.length < i
var numbers = [1,2,3,4]; var total = 0; for (var i= 0; i < numbers.length; i++){ total += numbers[i]; } console.log(total);
Your for loop is exiting immediately because of the condition由于条件,您的 for 循环立即退出
for (var i = 0; numbers.length < i; i++) {
Because numbers.length
(in this case) is 4, and i
is 0, the for loop never executes.因为
numbers.length
(在这种情况下)是 4,而i
是 0,for 循环永远不会执行。
You probably want it flipped around, to say something like你可能希望它翻转过来,说类似的话
for (var i = 0; i < numbers.length; i++) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.