javascript 当 for 循环处理对象数组时 forEach 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15846274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:18:14  来源:igfitidea点击:

forEach not working when for loop does with an array of objects

javascriptarraysfunctionfor-loopforeach

提问by GriffLab

I have an array like so

我有一个像这样的数组

var updates = [];

I then add stuff to the array like this

然后我像这样将东西添加到数组中

updates["func1"] = function () { x += 5 };

When I call the functions with a for loop it works as expected

当我用 for 循环调用函数时,它按预期工作

for(var update in updates) {
     updates[update]();
}

But when I use the forEach it doesn't work!?

但是当我使用 forEach 时它不起作用!?

updates.forEach(function (update) {

    update();
});

forEach definitely works in my browser which is google chrome, what am I doing wrong?

forEach 肯定可以在我的 google chrome 浏览器中运行,我做错了什么?

回答by ZER0

forEachiterates over indexesnot over properties. Your code:

forEach迭代indexesnot over properties。您的代码:

updates["func1"] = "something";

Adds a property to an object – that incidentally is an array – not an element to an array. In fact, it's equivalent to:

向一个对象添加一个属性——顺便说一下是一个数组——而不是数组的元素。事实上,它相当于:

updates.func1 = "something";

If you need something like an hashmap, then you can use a plain object instead:

如果你需要像 hashmap 这样的东西,那么你可以使用普通对象:

updates = {};

updates["func1"] = "something";

And then iterate using for…in, that shouldn't be used on arrays

然后迭代 using for…in不应在数组上使用

Or you can use Object.keysto retrieve the properties an iterate over them:

或者您可以使用Object.keys来检索属性并对其进行迭代:

Object.keys(updates).forEach(function(key) {
    console.log(key);
}); 

回答by James Montagne

You aren't adding the items to the array, you are adding object properties to your array object. for .. inwill return all properties, forEachonly iterates over array elements.

您不是将项目添加到数组中,而是将对象属性添加到数组对象中。 for .. in将返回所有属性,forEach只迭代数组元素。

To add to the array, you would do this:

要添加到数组,您可以这样做:

updates.push(function () { x += 5 });

If you intend to add in the way you are, then just use an object and not an array:

如果您打算按照您的方式添加,那么只需使用对象而不是数组:

var updates = {}

and then use for ... in.

然后使用for ... in.