Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript迭代与过滤器映射_Javascript - Fatal编程技术网

JavaScript迭代与过滤器映射

JavaScript迭代与过滤器映射,javascript,Javascript,我想知道这两者之间的区别: function doesCodeExist(arrvalidcodes, code) { var hit = arrvalidcodes.filter(function(item){ return (code === item) }).map(function(item){ return true; }); if (hit[0] === true) { return true; } else { return f

我想知道这两者之间的区别:

function doesCodeExist(arrvalidcodes, code) {

  var hit = arrvalidcodes.filter(function(item){
    return (code === item)
  }).map(function(item){
    return true;
  });
  if (hit[0] === true) {
    return true;
  } else {
    return false;
  }
}
这是:

function doesCodeExist(arrvalidcodes, code) {

  for (var i = 0; i < arrvalidcodes.lenght; i++) {
    if (arrvalidcodes[i] === code) {
      return true;
    }
  }
  return false;
}
函数doesCodeExist(arrvalidcodes,code){
对于(变量i=0;i
两个代码应该做相同的事情,如果代码在提供的数组中,只需返回
true
,否则返回
false

哪一种被认为是最具可读性的,哪一种方法更有效?

您可以使用

indexOf()
方法返回在数组中可以找到给定元素的第一个索引,如果该元素不存在,则返回
-1


或者使用ES6时,您的第一个代码当然更糟糕,因为它分配了各种无用的数组,并且不可读

如果需要语义ES5数组方法,请使用
一些

function doesCodeExist(arrvalidcodes, code) {
  return arrvalidcodes.some(function(item){
    return code === item;
  });
}

当然,对于严格的比较,您应该使用
indexOf
,或者您想要一个相同的值zero comparison use
includes

我想说,第二个块更有效,因为您一发现某个内容就存在for循环,而第一个部分在所有项目中循环(而且它也不可读。我当然更喜欢第二部分,你认为哪一部分更可读?如果(hit[0]==true){return true;},那么这个
如果(hit[0]==true){return false;}
可以缩写为:
return hit[0]==true;
@Craicerjack
hit[0]
不能是除
true
未定义
之外的任何内容(在后一种情况下,仅当
hit.length==0
)。无论哪种方法,像这样使用
.filter
.map
都是一种可怕的、非直观且效率低下的检查数组中是否存在元素的方法。IMHO,在这种情况下,使用
.indexOf
(或
。包括
(如果可用))比在
中使用自定义谓词函数要好得多。有些
-用回调替换一个完美的本机相等性测试毫无意义。@Alnitak是的,这就是我在上一段中的意思。但是对于自定义比较,应该使用
一些
而不是
过滤器
映射
。是的,绝对正确y
some
对于自定义比较器更好,但是对于纯相等测试更糟。
function doesCodeExist(arrvalidcodes, code) {
  return arrvalidcodes.some(function(item){
    return code === item;
  });
}