2017-06-12 90 views
0

作爲Udemy Web開發培訓營的代碼的一部分(由Colt Steele提供),我有以下JavaScript,它簡單地列出了數組中的項,更改console.log文本取決於布爾型「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); 
    } 
} 

我在這裏錯過了什麼?

非常感謝! 裏克

+0

嘛看起來你並沒有複製所有'movieArr [I] .hasWatched = TRUE; – epascarello

+2

*如果(movieArr [I] .hasWatched ==真){* theres區分*賦值*和*比較* –

+0

...或只是'如果(movieArr [i] .hasWatched)'。 –

回答

2

您將true分配給屬性,但您需要檢查值。您可以省略比較並直接使用該值。

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

爲了防止副作用,使用錯誤的分配中的條件下,你可以使用Yoda conditions(YC),帶有用於檢查交換條件,如

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

現在的條件拋出異常的不分配一個值。

在YC一個完整的工作檢查應該是這樣的聲明

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

,其中真正的檢查是多餘的,因爲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) { 

您每次分配hasWatchedtrue

0

你應該將hasWatched變量設置爲true,以便將其與真實值進行比較。

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

VS

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

+1

謝謝:) - 大約一個小時的挫折已經結束了! – RickHallett