2017-06-12 11 views
0

Udemy Web Development Bootcamp(Colt Steele)のコードの一部として、配列内のアイテムをリストする次のjavascriptを用意しています。ブール値「hasWatched」条件。 Console.logはすべての配列項目を真であるかのように返します。条件が配列の繰り返し内で常にtrueを返す場合

// 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); 
    } 
} 

ここでは何が欠けていますか?

多くの感謝! Rick

+0

あなたはそれをすべてコピーしなかったように見えますまあ 'movieArr [i]を.hasWatched = true'を – epascarello

+2

*もし(movieArr [i]が.hasWatched ==真){*は* *と*の比較*の違いを表します。 –

+0

...または単にif(movieArr [i] .hasWatched) 'です。 –

答えて

2

trueをプロパティに割り当てますが、値を確認する必要があります。比較を省略して値を直接使用することもできます。副作用を防ぐために

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

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

のように、チェックするための切り替え条件は今の状態が例外ANにはないスローでの条件で間違って割り当てて、あなたは、Yoda conditions(YC)を使用することができます値を割り当てます。

YCで完全な作業のチェックは、真のチェックが原因hasWatchedの与えられたと期待値と、不必要であるこの文

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

ようになります。

最終チェック条件が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) 
 
});

+0

ありがとう、ニーナ、それは非常に有用で、YCチェックについて学ぶことはクールな新しいことでした – RickHallett

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

は次のようになります

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

あなたの割り当てはhasWatchedからtrueまで毎回です。

0

hasWatched変数をtrueと比較する必要がある場合は、変数をtrueに設定しています。

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

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

+1

ありがとう:) - 約1時間の欲求不満は終わった! – RickHallett

関連する問題