在JavaScript中对空数组使用for循环 [英] Using a for each loop on an empty array in JavaScript

查看:905
本文介绍了在JavaScript中对空数组使用for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现我无法在javascript中的空数组上为每个循环使用a.谁能向我解释为什么?

I've found that I can't use a for each loop on an empty array in javascript. Can anyone explain to me why this is?

我已经在javascript中初始化了一个数组,如下所示:

I've initialized an array in javascript like so:

var arr = new Array(10);

当我对数组的每个循环使用a时,什么也没发生:

when I use a for each loop on the array nothing happens:

arr.forEach(function(i) {
    i = 0;
});

结果仍然是未定义值的数组:

the result is still an array of undefined values:

arr = [ , , , , , , , , , ];

我认为也许因为数组中的每个项目都是未定义的,所以它甚至不执行forEach.我认为它仍然会遍历未定义的项目.谁能解释为什么会这样? 这个问题不是在问如何最有效地用零填充数组,而是在询问有关每个循环和一个空数组的相互作用的详细信息..

I think that maybe since each item in the array is undefined, it doesn't even execute the forEach. I would think that it would still iterate through the undefined items. Can anyone explain why this is occurring? This question is not asking how to most efficiently fill an array with zeros, it's asking details on the interaction of a for each loop and an empty array.

推荐答案

您已经中途了!

我认为也许由于数组中的每个项目都是未定义的,所以它甚至不执行forEach.

I think that maybe since each item in the array is undefined, it doesn't even execute the forEach.

Array.prototype.forEach不访问已删除或消除的索引;这是一个称为 ellision 的过程.因此,它会执行,但会跳过每个元素.

Array.prototype.forEach does not visit indices which have been deleted or elided; this is a process called ellision. So, it executes, but skips over every element.

来自 MDN :

这篇关于在JavaScript中对空数组使用for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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