找出JavaScript数组是否包含值的最简洁有效的方法是什么?

这是我知道的唯一方法:

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

有没有更好、更简洁的方法来实现这一点?

这与堆栈溢出问题密切相关。在JavaScript数组中查找项目的最佳方法是什么?它解决了使用indexOf查找数组中的对象的问题。


当前回答

使用idnexOf()是一个很好的解决方案,但您应该隐藏嵌入的实现indexOf(()函数,该函数使用~运算符返回-1:

function include(arr,obj) { 
    return !!(~arr.indexOf(obj)); 
} 

其他回答

只是另一种选择

// usage: if ( ['a','b','c','d'].contains('b') ) { ... }
Array.prototype.contains = function(value){
    for (var key in this)
        if (this[key] === value) return true;
    return false;
}

要小心,因为用自定义方法重载javascript数组对象会破坏其他java脚本的行为,从而导致意外行为。

Use:

Array.prototype.contains = function(x){
  var retVal = -1;

  // x is a primitive type
  if(["string","number"].indexOf(typeof x)>=0 ){ retVal = this.indexOf(x);}

  // x is a function
  else if(typeof x =="function") for(var ix in this){
    if((this[ix]+"")==(x+"")) retVal = ix;
  }

  //x is an object...
  else {
    var sx=JSON.stringify(x);
    for(var ix in this){
      if(typeof this[ix] =="object" && JSON.stringify(this[ix])==sx) retVal = ix;
    }
  }

  //Return False if -1 else number if numeric otherwise string
  return (retVal === -1)?false : ( isNaN(+retVal) ? retVal : +retVal);
}

我知道这不是最好的方法,但由于没有本机的IComparable方法来在对象之间进行交互,我想这是比较数组中两个实体所能做到的。此外,扩展Array对象可能不是明智的做法,但有时也可以(如果您意识到这一点和权衡)。

使用idnexOf()是一个很好的解决方案,但您应该隐藏嵌入的实现indexOf(()函数,该函数使用~运算符返回-1:

function include(arr,obj) { 
    return !!(~arr.indexOf(obj)); 
} 

Javascript中查找数组是否包含值的最快方法是:

function existsInArrayForIgnoreDataType(arr, targetElem) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] == targetElem) return true
  }
  return false
 }

你可以在这里找到我做的完整研究。

Object.keys,用于获取对象的所有属性名称,并筛选与指定字符串完全或部分匹配的所有值。

函数filterByValue(数组,字符串){返回array.filter(o=>Object.keys(o).some(k=>o[k].toLowerCase().includes(string.toLoweCase()));}常量数组OfObject=[{name:“Paul”,country:'加拿大',}, {name:'Lea',国家:“意大利”,}, {name:“John”,country:'意大利'}];console.log(filterByValue(arrayOfObject,'lea'));//〔{名称:‘Lea’,国家:‘意大利’}〕console.log(filterByValue(arrayOfObject,'ita'));//[{名称:“Lea”,国家:“Italy”},{名称“John”,国家“Italy'”}]

您还可以按特定关键字进行筛选,例如。

Object.keys(o).some(k => o.country.toLowerCase().includes(string.toLowerCase())));

现在,您可以在过滤后检查数组计数,以检查值是否包含。

希望这有帮助。