forEach vs for loop ?? for循环似乎有效,但不适用于forEach。为什么?请有人解释一下吗?

时间:2017-02-06 23:17:32

标签: javascript arrays for-loop foreach

/ *请看看以下功能。它功能简单。我想迭代电影数组并返回元素;仅当元素的标题与传入的参数完全相同时才使用。否则在迭代结束时返回false 问题是,它总是返回false。但是,如果我使用常规forloop而不是forEach循环,它的工作完全正常..有人可以解释为什么这种情况??????先感谢您。 * /

function searchMovies(title) {
    movies.forEach(function(ele){
        if(ele.title === title){
            return ele;
        }
    });
return false;
}

//movies array
var movies = [
  {title: 'The Hobbit'},
  {title: 'The Great Gatsby'},
  {title: 'Gone with the Wind'}
];

//the following line calls the function
searchMovies('The Great Gatsby');

2 个答案:

答案 0 :(得分:3)

你从传递给forEach的回调中返回,forEach每次都忽略并调用回调到下一个元素。你需要的是像这样使用find

function searchMovies(title) {
    var found = movies.find(function(ele){
        return ele.title === title;
    });
    return found; // found will be either and item from the array (if find found something) or undefined (if it doesn't)
}

注1: movies数组应该在函数searchMovies之前定义,或者作为参数传递给它(最好的方法)。

注2:如果要返回所有匹配元素的数组(如果数组中有重复项并且您想要返回所有匹配元素),则使用filter ,使用相同的方式,它返回所有匹配元素的数组(如果没有匹配,则返回一个空元素。)

答案 1 :(得分:1)

因为你在forEach函数内部返回。

function searchMovies(title) {
    var foundMovie = false;
    movies.forEach(function(ele) {
        if (ele.title === title) {
            foundMovie = ele;
        }
    });
    return foundMovie;
}