简体   繁体   中英

Why can't I iterate over this array?

I am new to JavaScript and I don't know the reason why there is no output from this code.

function printArray(a) {
    for (var key in a) {
        console.log(a[key]);
    }
}
var a = new Array(10);
printArray(a);

Is something wrong?

There are no enumerable properties on an empty slots array like that. In addition, you almost never want to use for ( in ) loop for going over an array's indexes.

You should use a regular for loop, or Array.prototype.forEach() (if the array had values, of course).

function printArray(a) {
    for (var i = 0; i < a.length; i++) {
        console.log(a[i]);
    }
}
// or
function printArray(a) {
    a.forEach(function(i) {
        console.log(i);
    });
}

Keep in mind that Array.prototype.forEach() may not be supported in all your target platforms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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