“使用for循环遍历数组”初学者Java脚本

时间:2018-06-20 20:41:17

标签: for-loop

我想知道为什么我得到的结果是“您还没有看过”而不是“您已经看过”,因为“键属性”“已经看过”是设置为true的布尔值?为什么我会得到假的?

var movies=[
    { Title:"Superman",
      Rating:5,
      hasWatched: true,
    }
    ]

function allThem(movie){
    var result="You have ";
    for(var i=0; i < movie.length ; i++){
        if(movies.hasWatched){result += "watched";}else{result += "not seen";}console.log(result)};} 

allThem(movies) //--I'm calling the function here
 You have not seen //-- This the outcome should be "You have watched" instead of that.

2 个答案:

答案 0 :(得分:0)

您没有通过for循环正确引用电影

问题实际上在您的循环中,所以让我们直接看一下

function allThem(movie){
  var result="You have ";
  for(var i=0; i < movie.length ; i++){
    if(movies.hasWatched){
      result += "watched";
    }else{
      result += "not seen";
    }
    console.log(result)
  }
}

您会看到您正在检查数组movies.hasWatched属性,而不是电影本身。您需要使用声明的索引引用数组中的值:

function allThem(movie){
  var result="You have ";
  for(var i=0; i < movie.length ; i++){
    if(movie[i].hasWatched){ // notice the `[i]` added to this line
      result += "watched";
    }else{
      result += "not seen";
    }
    console.log(result)
  };
} 

当然,如果您有两部电影怎么办?您将分别输出You have watched,然后输出You have watched + notseen。我们可能应该添加一些识别信息

function allThem(movie){
  for(var i=0; i < movie.length ; i++){
    var result="You have "; // moved it in here so that each movie gets a new string
    if(movie[i].hasWatched){
      result += "watched";
    }else{
      result += "not seen";
    }
    result += ' ' + movie[i].Title;
    console.log(result);
  };
} 

现在每个电影都有不同的字符串了!


让我们看看使用更多更新的遍历方法Array.prototype.forEach的另一种处理方式:

var movies=[
  {
    Title:"Superman",
    Rating:5,
    hasWatched: true,
  },
  {
    Title:"Superman 2",
    hasWatched: false,
  }
]

function hasWatched(movie, index, array){
  var out = 'You have '
  if(movie.hasWatched){
    out += 'watched '
  } else {
    out += 'not seen '
  }
  console.log(out + movie.Title)
}

movies.forEach(hasWatched)
// You have watched Superman
// You have not seen Superman 2

有很多遍历数组的方法,包括Array.prototype.forEach()Array.prototype.map()Array.prototype.filter()and even more,这些数组在使用后几乎不会写for循环。

答案 1 :(得分:0)

我曾经做过一些研究,您完全正确,自上次检查以来,我已经有了很大的进步

var  movies=[
 {Title: "Superman", Rating: 5, hasWatched: true}1: {Title: "Batman", Rating: 5, 
 hasWatched: false}]                                                                                                       
    Array.prototype.myForEach = function(func){for(var i=0 ;i < this.length ; i++) 
    {func(this[i]);}} 

function movieOf(elem){ var result="You have ";if(elem.hasWatched){ result +="watched ";}else{result +="not seen ";} result += elem.Title;console.log(result)}

movies.myForEach(movieOf)/---This i call the function
 You have watched Superman/--These are  the outputs
 You have not seen Batman