我怎样才能遍历这些项目?
var userCache = {};
userCache['john'] = {ID: 234, name: 'john', ... };
userCache['mary'] = {ID: 567, name: 'mary', ... };
userCache['douglas'] = {ID: 42, name: 'douglas', ... };
长度属性不起作用?
userCache.length
最佳答案
您可以循环访问 userCache
对象的属性(john
、mary
和 douglas
),如下所示:
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()
很重要方法,判断对象是否具有指定的属性作为直接属性,而不是从对象的原型(prototype)链继承。
关于javascript - 如何循环遍历js对象中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2820573/