2017-09-26 181 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 + "."); 
    } 

} 

你只是缺少索引标识,同时访问