由 Array 构造函数创建的 undefined 数组上的 forEach [英] forEach on array of undefined created by Array constructor

查看:52
本文介绍了由 Array 构造函数创建的 undefined 数组上的 forEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道为什么不能在 undefined 数组上创建 forEach.

I am just wondering why it is not possible to make forEach on array of undefined.

代码:

var arr = new Array(5); // [undefined x 5]

//ES5 forEach
arr.forEach(function(elem, index, array) {
    console.log(index);
});

//underscore each
_.each(arr, function(elem, index, array) {
    console.log(index);
});

两个例子都没有执行函数.

Both examples do not execute function.

现在要制作 foreach,我必须制作:

Now to make foreach, I have to make:

var arr = [0,0,0,0,0];

然后在上面创建 forEach.

Then make forEach on it.

我正在尝试创建一个具有指定大小的数组并循环遍历它,避免 for 循环.我认为使用 forEach 比使用 for 循环更清晰.对于长度为 5 的数组,这不是问题,但是对于更大的数组会很丑.

I am trying to make an array with specified size and loop through it, avoiding for loop. I think that it is clearer using forEach than for loop. With array with length 5 it is not a problem, but it would be ugly with bigger arrays.

为什么在遍历未定义值数组时会出现问题?

Why there is a problem looping through array of undefined values ?

推荐答案

Array(5) 本质上等同于

var arr = []; 
arr.length = 5;

在 javascript 中,更改数组的长度不会为其数字属性设置任何值,也不会在数组对象中定义这些属性.所以数字属性是未定义的,而不是具有未定义的值.您可以使用以下方法进行检查:

In javascript changing array's length doesn't set any values for it's numeric properties nor does it define those properties in the array object. So numeric properties are undefined instead of having undefined value. You can check it by using:

Object.keys(arr)

当迭代 javascript 时会迭代数组的数字属性,所以如果这些不存在,就没有什么可以迭代的.

When iterating javascript iterates through numeric properties of the array, so if these don't exist, there is nothing to iterate over.

您可以通过以下方式进行检查:

You can check it by doing:

var arr = Array(5)

//prints nothing
arr.forEach(function(elem, index, array) {
    console.log(index);
});

arr[3] = 'hey'
//prints only 'hey' even though arr.length === 5
arr.forEach(function(elem, index, array) {
    console.log(index);
});

以下代码:

var arr = [undefined, undefined];

创建length ===2 的数组,并将数字属性 0 和 1 设置为 undefined.

这篇关于由 Array 构造函数创建的 undefined 数组上的 forEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆