'对于'循环没有正确循环通过对象数组

时间:2017-09-26 02:34:06

标签: javascript

当我运行非常简单的以下代码时,出于某种原因,我在浏览器控制台中得到以下结果:" 6您还没有看过undefined undefined。"有人能指出我的错误吗?



datalab: command not found




3 个答案:

答案 0 :(得分:3)

您有一个对象数组,因此您需要引用每个数组元素的索引。您还需要将循环减少一个,因为数组索引从零开始,但长度不是。

var movies = [{
    title: "The Mummy",
    hasWatched: true,
    stars: "5 stars"
  },

  {
    title: "About A Boy",
    hasWatched: true,
    stars: "5 stars"
  },


  {
    title: "It",
    hasWatched: false,
    stars: "5 stars"
  },


  {
    title: "Cleopatra",
    hasWatched: false,
    stars: "5 stars"
  }

];

for (var i = 0; i < movies.length; i++) {
  if (movies[i].hasWatched) {
    console.log("You have watched " + movies[i].title + " " + movies[i].stars + ".");
  } else {
    console.log("You have not watched " + movies[i].title + " " + movies[i].stars + ".");
  }

}

答案 1 :(得分:2)

for条件更改为i < movies.length;你有一个额外的迭代。 您还需要引用movies[i]来获取实际的电影,例如movies[i].title

在上面的示例中,最后一个索引是3(项目编号为0,1,2,3),但是您的循环将一直运行到4并且将尝试查找movies[4].title并返回undefined。

答案 2 :(得分:1)

for (var i = 0; i <= movies.length; i++) {
  if (movies[i].hasWatched) {
    console.log("You have watched " + movies[i].title + " " + movies[i].stars + ".");
 } else {
    console.log("You have not watched " + movies[i].title + " " + movies[i].stars + ".");
  }

}

您在访问

时只是缺少索引标识符