简体   繁体   English

使用顺序for循环遍历关联数组

[英]Iterate through associative array using sequential for loop

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: 使用For(... in Array)问题时的Mootools

As others have pointed out, this isn't an array. 正如其他人指出的那样,这不是数组。 This is a JavaScript object. 这是一个JavaScript对象。 To iterate over it, you will have to use the for...in loop. 要对其进行迭代,您将必须使用for ... in循环。 But to filter out the other properties, youw ill have to use hasOwnProperty . 但是要过滤掉其他属性,您将不得不使用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]);
}

http://jsfiddle.net/jeffshaver/HzLhe/3/ http://jsfiddle.net/jeffshaver/HzLhe/3/

JavaScript does not have the concept of associative arrays. JavaScript没有关联数组的概念。 Instead you simply have an object with enumerable properties, so use a for..in loop to iterate through them. 相反,您只是拥有一个具有可枚举属性的对象,因此请使用for..in循环迭代它们。 As stated above you may also want to perform a check with hasOwnProperty to ensure that you're not performing operations on inherited properties. 如上所述,您可能还想对hasOwnProperty执行检查,以确保您未对继承的属性执行操作。

for (var prop in obj){
    if (obj.hasOwnProperty(prop)){
        console.log(obj[prop]);
    }
}

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

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