javascript 使用顺序 for 循环遍历关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15809366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate through associative array using sequential for loop
提问by Jacob
I have a lot of data stored in associative array.
我有很多数据存储在关联数组中。
array = {'key':'value'};
How to loop throught an array like this using an normal for loop and not a loop like here: http://jsfiddle.net/HzLhe/
如何使用普通的 for 循环而不是像这里的循环来遍历这样的数组:http: //jsfiddle.net/HzLhe/
I don't want to use for-in because of this problems: Mootools when using For(...in Array) problem
我不想使用 for-in 因为这个问题: Mootools when using For(...in Array) 问题
回答by Jeff Shaver
As others have pointed out, this isn't an array. This is a JavaScript object. To iterate over it, you will have to use the for...in loop. But to filter out the other properties, youw ill have to use hasOwnProperty
.
正如其他人指出的那样,这不是一个数组。这是一个 JavaScript 对象。要迭代它,您必须使用 for...in 循环。但是要过滤掉其他属性,您将不得不使用hasOwnProperty
.
Example:
例子:
var obj={'key1': 'value1','key2':'value2'};
for (var index in obj) {
if (!obj.hasOwnProperty(index)) {
continue;
}
console.log(index);
console.log(obj[index]);
}
回答by Graham
JavaScript does not have the concept of associative arrays. Instead you simply have an object with enumerable properties, so use a for..in loop to iterate through them. As stated above you may also want to perform a check with hasOwnProperty
to ensure that you're not performing operations on inherited properties.
JavaScript 没有关联数组的概念。相反,您只需拥有一个具有可枚举属性的对象,因此请使用 for..in 循环来遍历它们。如上所述,您可能还想执行检查hasOwnProperty
以确保您没有对继承的属性执行操作。
for (var prop in obj){
if (obj.hasOwnProperty(prop)){
console.log(obj[prop]);
}
}