javascript - “for”循环未正确循环对象数组

标签 javascript

当我运行以下非常简单的代码时,由于某种原因,我在浏览器控制台中得到以下结果:“6 You have not saw undefined undefined.”谁能指出我的错误吗?

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.hasWatched) {
    console.log("You have watched " + movies.title + " " + movies.stars + ".");
  } else {
    console.log("You have not watched " + movies.title + " " + movies.stars + ".");
  }

}

最佳答案

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

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 + ".");
  }

}

关于javascript - “for”循环未正确循环对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46416968/

相关文章:

javascript - 如何检测长按按钮/图像

javascript - 将对象插入到数组 Javascript/JQuery 的特定位置

javascript - ImmutableJS 记录合并

javascript - 如何使用 Perl 和 Mechanize 在网页上单击此按钮

javascript - 密码强度验证器未提交表单

javascript - 在按键时禁用ajax表单按钮

javascript - 在 PHP 中使用 javascript 更改页面标题 'if'

javascript - 使用经典 asp 进行 Dreamweaver 回发

javascript - JQuery 彩色动画不能可靠地触发

javascript - noui slider 改变方向时按键错误