2017-09-26 92 views
0

當我運行非常簡單的下面的代碼時,出於某種原因,我在瀏覽器控制檯中得到以下結果:「6您尚未觀看undefined undefined。任何人都可以指出我的錯誤嗎?'for'循環沒有正確循環通過對象數組

var movies = [{ 
 
    title: "The Mummy", 
 
    hasWatched: true, 
 
    stars: "5 stars" 
 
    }, 
 

 
    { 
 
    title: "About A Boy", 
 
    hasWatched: true, 
 
    stars: "5 stars" 
 
    }, 
 

 

 
    { 
 
    title: "It", 
 
    hasWatched: false, 
 
    stars: "5 stars" 
 
    }, 
 

 

 
    { 
 
    title: "Cleopatra", 
 
    hasWatched: false, 
 
    stars: "5 stars" 
 
    } 
 

 
]; 
 

 
for (var i = 0; i <= movies.length; i++) { 
 
    if (movies.hasWatched) { 
 
    console.log("You have watched " + movies.title + " " + movies.stars + "."); 
 
    } else { 
 
    console.log("You have not watched " + movies.title + " " + movies.stars + "."); 
 
    } 
 

 
}

+0

'movies'是一個數組。你需要用'i'來索引它。即'電影[i] .hasWatched' – jlars62

回答

3

你有對象的數組,所以你需要引用每個數組元素的索引。由於數組索引是從零開始的,但是長度卻不是零,因此還需要將循環減少一。

var movies = [{ 
 
    title: "The Mummy", 
 
    hasWatched: true, 
 
    stars: "5 stars" 
 
    }, 
 

 
    { 
 
    title: "About A Boy", 
 
    hasWatched: true, 
 
    stars: "5 stars" 
 
    }, 
 

 

 
    { 
 
    title: "It", 
 
    hasWatched: false, 
 
    stars: "5 stars" 
 
    }, 
 

 

 
    { 
 
    title: "Cleopatra", 
 
    hasWatched: false, 
 
    stars: "5 stars" 
 
    } 
 

 
]; 
 

 
for (var i = 0; i < movies.length; i++) { 
 
    if (movies[i].hasWatched) { 
 
    console.log("You have watched " + movies[i].title + " " + movies[i].stars + "."); 
 
    } else { 
 
    console.log("You have not watched " + movies[i].title + " " + movies[i].stars + "."); 
 
    } 
 

 
}

2

更改for條件i < movies.length;你有一個額外的迭代。 而且您還需要參考movies[i]才能獲得實際的電影,例如movies[i].title

在上例中,最後一個索引是3(項目編號爲0,1,2,3),但是您的循環將一直持續到4,並且將嘗試查找movies[4].title並返回undefined。

1
for (var i = 0; i <= movies.length; i++) { 
    if (movies[i].hasWatched) { 
    console.log("You have watched " + movies[i].title + " " + movies[i].stars + "."); 
} else { 
    console.log("You have not watched " + movies[i].title + " " + movies[i].stars + "."); 
    } 

} 

你只是缺少索引標識,同時訪問