所以我試圖從一個json對象中通過一個for循環獲取一些數據,並且它一直返回undefined。這裏是我的代碼:Javascript json返回undefined
router.get('/', function(req, res, next) {
request('https://api.instagram.com/v1/media/popular?client_id=############', function (error, response, body) {
json = JSON.parse(body);
var popular_tags = [];
for (var key in json['data']){
tag = JSON.stringify(key['tags'])
popular_tags.push(tag)
}
console.log(popular_tags)
res.render('index', {title: body });
});
});
這是輸出我收到:
[ undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined ]
然而,當我嘗試
var popular_tags = [];
popular_tags.push(json['data'][0]['tags'])
console.log(popular_tags)
它會打印出我想要的東西。有什麼建議麼?當你說
for (var key in json['data'])
的key
通過對象json.data
的屬性名稱的迭代
感謝您的幫助! – 2015-04-01 00:25:00