简体   繁体   中英

Iterating through an objects values

Im working with OOP and looking at how to iterate through an objects values, as an example, this code:

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:

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. In addition, it's an ES5, and supported by all current browsers.

 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. In addition, since it's an ECMAScript 2017 Draft, IE and older browsers lack support.

 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 :

 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]); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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