如何在JavaScript中使用reduce而不是for循环构建contains函数?

hac*_*ann 5 javascript reduce for-loop functional-programming

我想这是两个问题.我仍然遇到使用reduce方法的问题,我得到了使用它的简单方法

reduce([1,2,3], function(a, b) { return a + b; }, 0); //6

使用除数字以外的任何东西真的让我很困惑.那么我将如何使用reduce代替for循环来构建contains函数?评论将不胜感激.谢谢你们.

function contains(collection, target) {
  for(var i=0; i < collection.length; i++){
    if(collection[i] === target){
      return true;
    }
  }
  return false;
}
contains([1, 2, 3, 4, 5], 4);
//true
Run Code Online (Sandbox Code Playgroud)

Sim*_*n H 2

这就是您所需要的:

function contains(collection, target) {
    return collection.reduce( function(acc, elem) {
       return acc || elem == target;
    }, false)
};
Run Code Online (Sandbox Code Playgroud)

正如阿达内奥所说,对于这个特定的问题可能有一种更简单的方法,但你标记了这个“函数式编程”,所以我猜你想更好地采用这种解决问题的方式,我完全赞同。