我从API中获取了一个对象列表,如下所示:
{
"results": [
{
"date": "2014-09-25 19:00:00",
"title": "Hitjeskanon"
},
{
"date": "2014-09-25 21:00:00",
"title": "Black & White ESN House & Techno"
},
{
"date": "2014-09-25 21:00:00",
"title": "Hit It!"
}
]
}
我现在从API中获取这些结果,并希望记录它们,我尝试如下:
$.ajax({
url: "/eventSearch/" + q,
cache: false,
success: function(result) {
console.log(result);
console.log(result['results']);
for (event in result['results']) {
console.log(event['title']);
}
}
});
在控制台中,我正确地看到包含前两个日志的对象,但console.log(event['title'])
仅打印出undefined
。
我在这里做错了什么?欢迎所有提示!
答案 0 :(得分:3)
result['results']
实际上是一个数组。所以,你应该像普通的for循环一样迭代它
for (var i = 0; i < result['results'].length; i += 1) {
console.log(result['results'][i]['title']);
}
或者你可以像这样使用Array.prototype.forEach
result['results'].forEach(function(currentObject) {
console.log(currentObject['title']);
});
此外,您可以使用点运算符访问属性,如此
console.log(result.results[i].title);
或
console.log(currentObject.title);
答案 1 :(得分:0)
你可以使用传统的for
循环,但如果你不需要随机访问(例如,results[2]
),你可以使用for...of
}语句(在ECMAScript6中引入)。在您的代码中,只需将for...in
更改为for...of
:
$.ajax({
url: "/eventSearch/" + q,
cache: false,
success: function(result) {
console.log(result);
console.log(result['results']);
for (event of result['results']) {
console.log(event['title']);
}
}
});
和@thefourtheye一样,您可以使用点运算符访问results
数组和事件的title
属性:
$.ajax({
url: "/eventSearch/" + q,
cache: false,
success: function(result) {
console.log(result);
console.log(result.results);
for (event of result.results) {
console.log(event.title);
}
}
});
此页面是一个很好的参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of