我有一个像这样的数组
var updates = [];
然后我像这样将数据添加到数组中
updates["func1"] = function () { x += 5 };
当我用for循环调用函数时,它按预期工作
for(var update in updates) {
updates[update]();
}
但是,当我使用forEach它不起作用!?
updates.forEach(function (update) {
update();
});
forEach绝对可以在我的浏览器中使用google chrome,我做错了什么?
解决方法
forEach遍历索引而不是属性.你的代码:
updates["func1"] = "something";
向对象添加属性 – 顺便提一下,它是一个数组 – 而不是数组的元素.
实际上,它相当于:
updates.func1 = "something";
如果你需要类似hashmap的东西,那么你可以使用普通对象:
updates = {};
updates["func1"] = "something";
然后迭代使用for … in,即shouldn’t be used on arrays
或者您可以使用Object.keys检索属性并迭代它们:
Object.keys(updates).forEach(function(key) {
console.log(key);
});