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

这是我知道的唯一方法:

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

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

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


当前回答

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对象可能不是明智的做法,但有时也可以(如果您意识到这一点和权衡)。

其他回答

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())));

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

希望这有帮助。

函数countArray(originalArray){var压缩=[];//复制输入数组var copyArray=originalArray.slice(0);//第一个循环遍历每个元素for(var i=0;i<originalArray.length;i++){变量计数=0; //在副本中的每个元素上循环,看看是否相同for(var w=0;w<copyArray.length;w++){if(originalArray[i]==copyArray[w]){//增加发现重复的次数计数++;//将项设置为未定义delete copyArray[w];}}如果(计数>0){var a=新对象();a.value=原始数组[i];a.count=计数;按压(a);}}返回压缩;};//应该是这样的:var testArray=新数组(“狗”、“狗”,“猫”,“水牛”,“狼”、“猫”、“老虎”、“猫咪”);var newArray=countArray(testArray);console.log(newArray);

使用Array.indexOf(对象)。对于ECMA7,可以使用Array.includes(对象)。使用ECMA 6,可以使用Array.find(FunctionName),其中FunctionName是用户定义函数以搜索数组中的对象。希望这有帮助!

使用Array.prototype.includes,例如:

常量水果=['conot','香蕉','苹果']const doesFruitsHaveCoconut=水果.包括('conot')//trueconsole.log(doesFruitsHaveCoconut)

可以从MDN阅读此文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

假设您定义了这样一个数组:

const array = [1, 2, 3, 4]

下面是三种检查其中是否有3的方法。所有这些都返回true或false。

本机阵列方法(自ES2016以来)(兼容性表)

array.includes(3) // true

作为自定义数组方法(ES2016之前)

// Prefixing the method with '_' to avoid name clashes
Object.defineProperty(Array.prototype, '_includes', { value: function (v) { return this.indexOf(v) !== -1 }})
array._includes(3) // true

简单的功能

const includes = (a, v) => a.indexOf(v) !== -1
includes(array, 3) // true