如何遍历js对象中的项目? [英] How to loop through items in a js object?

查看:127
本文介绍了如何遍历js对象中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何遍历这些项目?

var userCache = {};
userCache['john']     = {ID: 234, name: 'john', ... };
userCache['mary']     = {ID: 567, name: 'mary', ... };
userCache['douglas']  = {ID: 42,  name: 'douglas', ... };

length属性不起作用?

the length property doesn't work?

userCache.length

推荐答案

您可以如下循环遍历userCache对象的属性(johnmarydouglas):

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;
        //     ...
    }
}

使用 hasOwnProperty() 很重要方法,以确定对象是否具有指定的属性作为直接属性,而不是继承自对象的原型链.

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.

这篇关于如何遍历js对象中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆