In nodeJs is there a way to loop through an array without using array size?

后端 未结 8 914
后悔当初
后悔当初 2021-02-01 11:56

Let\'s say I have

myArray = [\'item1\', \'item2\']

I tried

for (var item in myArray) {console.log(item)}

It

8条回答
  •  生来不讨喜
    2021-02-01 12:33

    In ES5 there is no efficient way to iterate over a sparse array without using the length property. In ES6 you can use for...of. Take this examples:

    'use strict';
    
    var arr = ['one', 'two', undefined, 3, 4],
        output;
    
    arr[6] = 'five';
    
    output = '';
    arr.forEach(function (val) {
        output += val + ' ';
    });
    console.log(output);
    
    output = '';
    for (var i = 0; i < arr.length; i++) {
        output += arr[i] + ' ';
    }
    console.log(output);
    
    output = '';
    for (var val of arr) {
        output += val + ' ';
    };
    console.log(output);
    
    

    All array methods which you can use to iterate safely over dense arrays use the length property of an object created by calling ToObject internaly. See for instance the algorithm used in the forEach method: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18 However in es6, you can use for...of safely for iterating over sparse arrays.

    See also Are Javascript arrays sparse?.

提交回复
热议问题