如何在for-in循环中打印出对象属性?

时间:2014-10-01 14:34:09

标签: javascript logging for-loop

我从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

我在这里做错了什么?欢迎所有提示!

2 个答案:

答案 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