开发者

difference between using arr[i] and arr.length in the for loop definition in javascript

I came across something I've never seen before and I like it. check examples below:

开发者_Python百科
var arr = ['un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept'];

for(var i = 0; arr[i]; i++){
  console.log( arr[i] );
}

instead of:

for(var i = 0; i < arr.length; i++){
  console.log( arr[i] );
}

But they both achieve the same result, which is to output a list of array.

My question is, what's the difference (or similarity) between using 'arr[i]' and 'arr.length' in the for loop declaration?

Many thanks


var arr = ['un', 'deux', 'trois', null, 'cinq', 'six', 'sept'];

How about now?

delete arr[2];

How about now?

The difference shows up as soon as you have falsy values in the array, or discontinuities in keys (such as those created by using the delete operator). The length loop will yield the falsy value and continue, the other one will stop.


i < arr.length

this statement checks in every loop if i is smaller then the length of arr

arr[i]

here, every loop cycle checks if arr at position i is truthy.


Let's ask jsperf.com for this.


Using arr[i] as the continue condition checks the truthiness of the element at that position in the array. This is a cute trick, but won't work if you want to iterate over arrays containing falsy values, like

[1, 4, 6, 0, 3, 9]
// or
[true, 'seven', false, -1, {foo: 'bar'}]

Using i < arr.length checks that the current index is less than the total length of the array.


The for loop iterates as long as the condition part of it is true. First time the condition is false the loop stops.

arr[i] is true as long as the value is not one of the following: false, 0, empty string, null, undefined, NaN

i < arr.length checks that i is less than the size of the array, which is what you should do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜