2013-09-27 21 views
0

財產「XXX」我獲得這樣的@attr值:Json的錯誤:無法讀取的不確定

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

也能正常工作時,該屬性出現在JSON,但如果它不在那裏,我得到一個錯誤:

Uncaught TypeError: Cannot read property 'nowplaying' of undefined 

如何避免此錯誤?看到

+4

顯示您的'項目'。 –

+0

不確定我是否遵循,我無法控制json中的attrr,我正在使用的api在音樂播放時添加它,當它不在時刪除它。 – user1059511

回答

3
if (item['@attr']){ 
    var nowPlaying = item['@attr']['nowplaying']); 
} 
1

測試是否item['@attr']有您嘗試訪問它的任何屬性之前,可以有屬性的值。

if (item['@attr']) { 
    whatever(item['@attr']['nowplaying']); 
} 
相關問題