2017-05-30 91 views
-1
var movies = [ 
    { 
     title: "Silence of the Lambs", 
     rating: "5 stars", 
     hasWatched: true 
    }, 

    { 
     title: "Frozen", 
     rating: "4 stars", 
     hasWatched: false 

    }, 

    { 
     title: "Inception", 
     rating: "1 stars", 
     hasWatched: true 
    } 
] 

for (i=0; i<movies.length; i++){ 
    var result = "You have " 
    if (movies[i].hasWatched=true) { 
     result += "seen "; 
    } else { 
     result += "not seen "; 
    } 

    console.log(result + movies[i].title + " - " + movies[i].rating) 
} 

我試圖打印「你已經看過這部電影等」如果hasWatched = true並且「你還沒有看過這部電影等」如果hasWatched = false。問題是,在這個版本中,它總是打印「看到」,即使是「凍結」。我試圖在if語句中加入「movies [i] .hasWatched = false」,在這種情況下,它總是打印出未看到的。可能是什麼問題呢?不能做出正確的如果陳述與對象相關

編輯:感謝球員這是一個非常愚蠢的錯誤。 Ty大家。

+0

'='應該是''==或更好的''===重複 – Andreas

+0

https://stackoverflow.com/questions/13851399/javascript-if-statements-not-working。 – 2017-05-30 06:37:37

+0

任何棉絨都會挑選它。 – 2017-05-30 06:40:24

回答

-1

請更新您的代碼

var result = "You have "; 
for (i=0; i<movies.length; i++){ 
    if (movies[i].hasWatched == true) { // OR if (movies[i].hasWatched) { 
     result += "seen "; 
    } else { 
     result += "not seen "; 
    } 

    console.log(result + movies[i].title + " - " + movies[i].rating) 
} 
-1

試試這個

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

使用==中,如果條件

+0

@torazaburo對此感到抱歉。其實我使用satck overflow移動應用程序,這很難在這個應用程序中縮進代碼。 –