如何在javascript中迭代(键,值)? [英] How to iterate (keys, values) in javascript?
问题描述
我的字典格式为
dictionary = {0: {object}, 1:{object}, 2:{object}}
如何通过执行类似
How can I iterate through this dictionary by doing something like
for((key,value) in dictionary){
//Do stuff where key would be 0 and value would be the object
}
推荐答案
tl;博士
- 在ECMAScript 5中,它是不可能的。
- 在ECMAScript 2015中,可以使用
Map
s。 - 在ECMAScript 2017中,它随时可用。
- In ECMAScript 5, it is not possible.
- In ECMAScript 2015, it is possible with
Map
s. - In ECMAScript 2017, it would be readily available.
ECMAScript 5:
不,对象无法实现。
您应该使用 for..in
,或 Object.keys
,像这样
You should either iterate with for..in
, or Object.keys
, like this
for (var key in dictionary) {
// check if the property/key is defined in the object itself, not in parent
if (dictionary.hasOwnProperty(key)) {
console.log(key, dictionary[key]);
}
}
注意: 如果
上面的条件是必要的,只有当你想要迭代属于 dictionary
对象的属性时。因为 for..in
将遍历所有继承的可枚举属性。
Note: The if
condition above is necessary, only if you want to iterate the properties which are dictionary
object's very own. Because for..in
will iterate through all the inherited enumerable properties.
或
Object.keys(dictionary).forEach(function(key) {
console.log(key, dictionary[key]);
});
ECMAScript 2015
在ECMAScript 2015中,您可以使用 Map
对象并使用 Map.prototype.entries
。从该页面引用示例,
In ECMAScript 2015, you can use Map
objects and iterate them with Map.prototype.entries
. Quoting example from that page,
var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
var mapIter = myMap.entries();
console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]
或者用 for..of
,像这样
Or iterate with for..of
, like this
'use strict';
var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
for (const entry of myMap.entries()) {
console.log(entry);
}
输出
[ '0', 'foo' ]
[ 1, 'bar' ]
[ {}, 'baz' ]
或
for (const [key, value] of myMap.entries()) {
console.log(key, value);
}
输出
0 foo
1 bar
{} baz
ECMAScript 2017
ECMAScript 2017将引入一个新功能 Object.entries
。您可以使用它来根据需要迭代对象。
ECMAScript 2017 would introduce a new function Object.entries
. You can use this to iterate the object as you wanted.
'use strict';
const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
输出
a 1
b 2
c 3
这篇关于如何在javascript中迭代(键,值)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!