简体   繁体   English

遍历对象值

[英]Iterating through an objects values

Im working with OOP and looking at how to iterate through an objects values, as an example, this code: 我正在与OOP一起工作,并研究如何遍历对象值,例如以下代码:

var numbers = {
    one: "number one",
    two: "number two",
    three: "number three",
    four: "number four"
};

and to iterate through its values, i got this: 并通过其值进行迭代,我得到了这个:

for(var index in numbers){
    var x = index;
    console.log(numbers[x]);    
}

Whilst looking a bit deeper and researching, i saw on mozillla.org that i can also iterate through an objects values like this: 在进行更深入的研究和研究的同时,我在mozillla.org上看到,我还可以迭代如下这样的对象值:

console.log(Object.values(numbers));

My question is, is there any benefit to one over the other? 我的问题是,一个相对于另一个有什么好处吗? In everyday programming would one use one over the other? 在日常编程中,一个人会优先使用另一个人吗?

The for...in loop iterates over the an object enumerable properties, including inherited properties. for...in循环遍历对象的可枚举属性,包括继承的属性。 In addition, it's an ES5, and supported by all current browsers. 另外,它是ES5,目前所有浏览器都支持。

 var obj1 = { a: 1, b: 2 }; var obj2 = Object.create(obj1); obj2.c = 3; for (var key in obj2) { console.log(obj2[key]); } 

Object#values creates an array of the object own properties (not inherited ones), and doesn't iterate them. Object#values创建一个由对象自身属性(不是继承的属性)组成的数组,并且不会对其进行迭代。 In addition, since it's an ECMAScript 2017 Draft, IE and older browsers lack support. 此外,由于它是ECMAScript 2017草案,因此IE和较旧的浏览器缺少支持。

 var obj1 = { a: 1, b: 2 }; var obj2 = Object.create(obj1); obj2.c = 3; console.log(Object.values(obj2)); 

If you want to iterate the object's own properties, and support older browsers, you can use Object#keys with an array iteration method, such as Array#forEach : 如果要迭代对象本身的属性并支持较旧的浏览器,则可以将Object#keys与数组迭代方法一起使用,例如Array#forEach

 var obj1 = { a: 1, b: 2 }; var obj2 = Object.create(obj1); obj2.c = 3; var result = Object.keys(obj2).forEach(function(key) { console.log(obj2[key]); }); 

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

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