JavaScript array iteration - MDN example

旧巷老猫 提交于 2019-12-25 04:13:48

问题


I was reading the re-introduction to JavaScript on the MDN website and came across this example in the Array section:

for (var i = 0, item; item = a[i++];){
   // Do something with item
}

Where "a[]" is an array being looped over.

I am confused about the value that "item" will have in its first iteration. As i=0 and item is at first undefined, then when it is assigned the value of a[i++] wouldn't the iteration start from i=1, which would mean that the iteration would start from the second element in the a[] array -> a[1], skipping over the first element a[0] entirely?


回答1:


i++ is the post increment operator, which means that it increments i by 1 but evaluates to the old (non-incremented) value.

> i = 0
  0
> i++
  0
> i
  1



回答2:


i++ is post increment (see other answers) and item will not be undefined, because the predicate (the second part in the for loop) is executed before each iteration.

for (var i = 0, item ; item = a[i++];) {

will evaluate to:

var i = 0;
var item;

item = a[i];  // loop
i += 1
if (!item) // exit loop
// loop body
// start again at loop

The problem with this syntax is, that if a value in a is falsy, the loop will terminate prematurely.

var a = [1,2,0,3,4];
for (var i = 0, item ; item = a[i++];) {
   console.log(item);
}

Will output "1 2" because "0" is falsy and the loop terminates




回答3:


i++ means that javascript reads the i value and then increments it



来源:https://stackoverflow.com/questions/16526670/javascript-array-iteration-mdn-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!