如果condition总是在数组迭代中返回true

时间:2017-06-12 16:39:12

标签: javascript arrays object if-statement foreach

作为Udemy Web Development Bootcamp(由Colt Steele)编写的代码的一部分,我有以下javascript,它只是列出数组中的项目,根据布尔“hasWatched”条件更改console.log文本。就目前而言,console.log返回所有数组项,就像它们是真的一样。

// Create an array of objects. Each movie should have a title, rating and hasWatched properties. Iterate through the array and print out results and whether it has been hasWatched

var movieArr = [
    {
        title: "LOTR", 
        rating: 5, 
        hasWatched: true
    },
    {
        title: "Fast and the Furious", 
        hasWatched: false, 
        rating: 1
    },
    {
        title: "Let the Right One In", 
        rating: 5, 
        hasWatched: false
    }
]


for(i = 0; i < movieArr.length; i++){
    if(movieArr[i].hasWatched = true){
        console.log("You have seen " + movieArr[i].title + ": Rating: " + movieArr[i].rating);
    } else {
        console.log("You have not seen " + movieArr[i].title + ": Rating: " + movieArr[i].rating);
    }
}

我在这里缺少什么?

非常感谢! 瑞克

3 个答案:

答案 0 :(得分:2)

You assign true to the property, but you need to check the value. You could omit the comparison and use the value directly.

if (movieArr[i].hasWatched = true) {
//                         ^

To prevent side effects, with wrong assignments in conditions, you could use Yoda conditions (YC), with a switched condition for checking, like

if (true = movieArr[i].hasWatched) { // throws: Invalid left-hand side in assignment 

Now the condition throws an exception an does not assign a value.

A complete working check in YC would look like this statement

if (true == movieArr[i].hasWatched) {

where the check for true is superfluous, because of the given and expected values of hasWatched.

The final checking condition uses the value and checks for truthyness:

if (movieArr[i].hasWatched) {

var movieArr = [{ title: "LOTR", rating: 5, hasWatched: true }, { title: "Fast and the Furious", hasWatched: false, rating: 1 }, { title: "Let the Right One In", rating: 5, hasWatched: false }];

//first attempt
for (i = 0; i < movieArr.length; i++) {
  if (movieArr[i].hasWatched) {
    console.log("You have seen " + movieArr[i].title + ": Rating: " + movieArr[i].rating);
  } else {
    console.log("You have not seen " + movieArr[i].title + ": Rating: " + movieArr[i].rating);
  }
}

//second attempt 
movieArr.forEach(function(i) {
  var result = "You have ";
  if (i.hasWatched) {
    result += "watched ";
  } else {
    result += "not watched ";
  }
  result += "\"" + i.title + "\" - ";
  result += i.rating + " stars";
  console.log(result)
});

答案 1 :(得分:0)

if (movieArr[i].hasWatched = true) {

Should be:

if (movieArr[i].hasWatched == true) {

Your assigning hasWatched to true every time.

答案 2 :(得分:0)

You're setting the hasWatched variable to true when you should be comparing it to true.

if (movieArr[i].hasWatched = true) {

vs

if (movieArr[i].hasWatched == true) {