Bla*_*man 1 javascript json loops
我怎么能循环这些项目?
var userCache = {};
userCache['john'] = {ID: 234, name: 'john', ... };
userCache['mary'] = {ID: 567, name: 'mary', ... };
userCache['douglas'] = {ID: 42, name: 'douglas', ... };
Run Code Online (Sandbox Code Playgroud)
长度属性不起作用?
userCache.length
Run Code Online (Sandbox Code Playgroud)
您可以循环遍历对象的属性(john,mary和douglas),userCache如下所示:
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;
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
使用该hasOwnProperty()方法很重要,以确定对象是否具有指定属性作为直接属性,而不是从对象的原型链继承.