开发者

Access JS object with a key

I can access a value like driver.my_friends["793659690"].name but now I am using it in a loop where key will hold the key.

driver.my_friends[key].name doesn't work. Says undefined, and driver.my_friends["key"].name will look for a key named key. So how do I use it so that the variable开发者_开发问答 of the variable is evaluated too.


when you're iterating over an object's properties, some "garbage" may get into "key" variable. I would suggest the following:

for (var key in driver.my_friends) {
  if (key && driver.my_friends[key] && driver.my_friends[key].name) {
    // Do what you need here
  }
}

Also, make sure that when the value of driver.my_friends[key] gets set, the key is the same as the one used for reading it


driver.my_friends[key].name is the right way. It is possible that no key like key exists in driver.my_friends =) and/or that .name doesn't exist in that object.

You can debug that very easily:

console.log(driver.my_friends[key]);
console.log(driver.my_friends[key].name);

Even IE8 has a console like that.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜