开发者

How to loop through items in a js object?

how can I loop through these items?

var userCache = {};
userCache['john']     = {ID: 234, name: 'john', ... };
userCache['mary']     = {ID: 567, name: 'm开发者_运维知识库ary', ... };
userCache['douglas']  = {ID: 42,  name: 'douglas', ... };

the length property doesn't work?

userCache.length


You can loop over the properties (john, mary and douglas) of your userCache object as follows:

for (var prop in userCache) {
    if (userCache.hasOwnProperty(prop)) {
        // You will get each key of the object in "prop".
        // Therefore to access your items you should be using:
        //     userCache[prop].name;
        //     userCache[prop].ID;
        //     ...
    }
}

It is important to use the hasOwnProperty() method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.


for(var i in userCache){
   alert(i+'='+userCache[i]);
}


For this you would use a for.. in loop

for (var prop in userCache) {
    if (userCache.hasOwnProperty(prop)) {
        alert("userCache has property " + prop + " with value " + userCache[prop]);
    }
}

The `.hasOwnProperty is needed to avoid members inherited through the prototype chain.


there's no length property because you're not using an indexed array.

see here for iterating over the properties.

Difference in JSON objects using Javascript/JQuery

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜