在JavaScript中循环遍历对象数组

时间:2017-10-27 00:16:24

标签: javascript arrays javascript-objects

我想找到所有喜欢的总和。我得到的错误是帖子不存在。 User是一个具有posts属性的对象,它是一个对象数组。我如何访问likes属性。谢谢

var sum = 0; //initialize sum
    //create user object
    var user = {
        posts: [
          {
           likes: 10
         }
          {
           likes: 15
         }

    ]
    }
    //Getting the sum of all likes. But doesn't work.
    for(i = 0; i < posts.length; i++) {
        sum += user.posts[i].likes;
    }
    return sum;

4 个答案:

答案 0 :(得分:0)

这是正确的代码:

var sum = 0; //initialize sum
//create user object
var user = {
    posts: [{
            likes: 10
        },
        {
            likes: 15
        }

    ]
}
//Getting the sum of all likes. But doesn't work.
for (var i = 0; i < user.posts.length; i++) {
    sum += user.posts[i].likes;
}
console.log(sum);

答案 1 :(得分:0)

你不能像posts.length那样访问对象属性,它会引发你undefined,你需要使用user.posts.length

for(var i=; i<user.posts.length; i++){
  sum += user.posts[i].likes;
}
return sum;

答案 2 :(得分:0)

reduce()可用于更轻松的聚合:

var user = { posts: [ { likes: 10 }, { likes: 15 } ] }

var sum = user.posts.reduce((s, o) => s + o.likes, 0)

console.log(sum)

答案 3 :(得分:0)

更简单而不是功能

&#13;
&#13;
var sum = 0;
var user = {
    posts: [
      {
       likes: 10
     },
      {
       likes: 15
     }

]
}

user["posts"].map(ele => sum=+ele["likes"]);
console.log(sum);
&#13;
&#13;
&#13;