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