【问题标题】:forEach vs for loop?? for loop seems to work, but not with forEach. Why? Please can someone explain?forEach vs for 循环?? for 循环似乎有效,但不适用于 forEach。为什么?请问有人可以解释吗?
【发布时间】:2017-06-24 01:24:41
【问题描述】:

/*请看下面的函数。它是一个简单的功能。我想遍历电影数组并返回元素;仅当元素的标题与传入的参数完全相同时。否则在迭代结束时返回 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');

【问题讨论】:

    标签: javascript arrays for-loop foreach


    【解决方案1】:

    您从传递给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,它以相同的方式使用,它返回一个包含所有匹配元素的数组(如果没有匹配则返回一个空数组)。

    【讨论】:

      【解决方案2】:

      因为您在 forEach 函数中返回。

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

      【讨论】:

      • 注意,这将找到 last 匹配而不是 first 可能不需要
      • @Phil 会循环遍历整个数组,即使找到的元素在第一个索引中!!
      • @Phil 和易卜拉欣,你是对的。我只是向他们展示如何使用他们尝试过的 forEach 使其工作:)
      猜你喜欢
      • 2021-11-06
      • 2019-09-14
      • 2012-10-02
      • 2020-06-14
      • 1970-01-01
      • 2020-05-04
      • 2013-07-20
      • 2015-10-16
      • 2019-10-01
      相关资源
      最近更新 更多