简体   繁体   English

为什么不能为每个对象迭代对象

[英]Why cant I iterate over Object with for Each

I am trying to iterate over an object with the forEach array method. 我正在尝试使用forEach数组方法遍历对象。

var obj = {"a":1, "b":2, "c":3};
[].forEach.call(obj, function(n, key) {
    console.log(key, n)
})

should Print 应该打印

a:1 a:1

b:2 乙:2

c:3 c:3

This doesn't work as it returns undefined in the debugger even when I artificially add a length property to the obj 这是行不通的,因为即使我人为在obj中添加length属性,它也会在调试器中返回undefined。

obj.length = 3;

How do I make this object array like so i can call array method like foreach on the object. 我如何使该对象数组像这样,以便可以在对象上调用诸如foreach之类的数组方法。 I am aware there are other ways to iterate over an object was just wondering what I was doing wrong in this scenario. 我知道还有其他方法可以迭代对象,只是想知道在这种情况下我做错了什么。

Array.prototype.forEach() will only work on arrays and not on objects. Array.prototype.forEach()仅适用于数组,不适用于对象。 You could use Object.keys() to loop over the object's own enumerable properties: 您可以使用Object.keys()遍历对象自身的可枚举属性:

var obj = {"a":1, "b":2, "c":3};

Object.keys(obj).forEach(function(key) {
    console.log(key, obj[key]);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM