我在JavaScript中有一个对象:
{
abc: '...',
bca: '...',
zzz: '...',
xxx: '...',
ccc: '...',
// ...
}
我想用一个for循环来获取它的属性。我想要迭代它的部分(不是所有的对象属性一次)。
对于一个简单的数组,我可以用一个标准的for循环来做:
for (i = 0; i < 100; i++) { ... } // first part
for (i = 100; i < 300; i++) { ... } // second
for (i = 300; i < arr.length; i++) { ... } // last
但是如何对对象进行处理呢?
唯一可靠的方法是将对象数据保存到2个数组中,一个是键数组,另一个是数据数组:
var keys = [];
var data = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
data.push(obj[key]); // Not necessary, but cleaner, in my opinion. See the example below.
}
}
然后你可以迭代数组,就像你通常会:
for(var i = 0; i < 100; i++){
console.log(keys[i], data[i]);
//or
console.log(keys[i], obj[keys[i]]); // harder to read, I think.
}
for(var i = 100; i < 300; i++){
console.log(keys[i], data[i]);
}
我没有使用Object.keys(obj),因为那是IE 9+。
有了新的ES6/ES2015特性,你不再需要使用对象来遍历散列。你可以使用地图。Javascript地图保持键的插入顺序,这意味着你可以迭代它们,而不必检查hasOwnProperty,这一直是一个真正的黑客。
迭代一个地图:
var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
for (var [key, value] of myMap) {
console.log(key + " = " + value);
}
// Will show 2 logs; first with "0 = zero" and second with "1 = one"
for (var key of myMap.keys()) {
console.log(key);
}
// Will show 2 logs; first with "0" and second with "1"
for (var value of myMap.values()) {
console.log(value);
}
// Will show 2 logs; first with "zero" and second with "one"
for (var [key, value] of myMap.entries()) {
console.log(key + " = " + value);
}
// Will show 2 logs; first with "0 = zero" and second with "1 = one"
或使用forEach:
myMap.forEach(function(value, key) {
console.log(key + " = " + value);
}, myMap)
// Will show 2 logs; first with "0 = zero" and second with "1 = one"