0

我正在获得这样的@attr 值:

item['@attr']['nowplaying']

当属性存在于 json 中时,这可以正常工作,但如果它不存在,我会收到错误消息:

Uncaught TypeError: Cannot read property 'nowplaying' of undefined 

我怎样才能避免这个错误?

4

2 回答 2

3
if (item['@attr']){
    var nowPlaying = item['@attr']['nowplaying']);
}
于 2013-09-27T09:04:20.223 回答
1

Test to see if item['@attr'] has a value that can have properties before you try to access any properties of it.

if (item['@attr']) {
   whatever(item['@attr']['nowplaying']);
}
于 2013-09-27T09:04:29.277 回答