简体   繁体   English

JavaScript 循环不起作用(学习JS)

[英]JavaScript loop doesn't work (learning JS)

Coming from a PHP background, I'm now learning JS, and I don't understand why this piece of code doesn't work:来自PHP背景,现在正在学习JS,不明白为什么这段代码不起作用:

 let i = 0; let arr = []; while(i < 8){ arr[i] = i; i++; } for(i = 0; arr[i]; i++) { console.log("Result:", arr[i]); }

From my point of view, this code is logic:从我的角度来看,这段代码是逻辑:

  1. I declare all my variables我声明了我所有的变量
  2. I put some random values in the array (just to fill it with something)我在数组中放了一些随机值(只是为了填充它)
  3. I want to console.log each element of the array while the condition is true我想在条件为真时 console.log 数组的每个元素

I know that i equals to 8 after the while loop, but even an " i=0 " before the for doesn't solve the issue (BTW why the i = 0 inside the for initialisation doesn't set it to 0?)我知道在 while 循环之后i等于8 ,但是即使在 for 之前的“ i=0 ”也不能解决问题(顺便说一句,为什么 for 初始化中的 i = 0 没有将其设置为 0?)

Can someone explain me what breaks the code?有人可以解释一下是什么破坏了代码吗?

for loops run until the condition is not true. for循环一直运行,直到条件不成立。

The first time around the loop i is 0 so arr[i] is arr[0] which you've populated with a 0 .第一次围绕循环i0所以arr[i]arr[0]你已经填充了0

0 is a false value, so the condition is false and the loop ends before the first iteration. 0是假值,因此条件为假,循环在第一次迭代之前结束。

You probably want the condition to be i < arr.length .您可能希望条件为i < arr.length

In your first look you set arr[i] = i .在您的第一眼中,您设置了arr[i] = i In the second loop your condition is arr[i] , and on the first iteration i = 0 , which means arr[i] is 0 which evaluates to false causing your loop to exit.在第二个循环中,您的条件是arr[i] ,并且在第一次迭代中i = 0 ,这意味着arr[i]为 0 ,其计算结果为 false 导致您的循环退出。

for loop condition is not correct, if you would like to console.log all values of array, you can use length() property to check the length if array and check in the for loop condition. for 循环条件不正确,如果要控制台记录数组的所有值,可以使用 length() 属性检查数组的长度并检查 for 循环条件。

 let i = 0; let arr = []; while(i < 8){ arr[i] = i; i++; } for(i = 0; i < arr.length; i++) { console.log("Result:", arr[i]); }

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

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