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

这是我知道的唯一方法:

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

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

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


当前回答

这可能是一个详细而简单的解决方案。

//plain array
var arr = ['a', 'b', 'c'];
var check = arr.includes('a');
console.log(check); //returns true
if (check)
{
   // value exists in array
   //write some codes
}

// array with objects
var arr = [
      {x:'a', y:'b'},
      {x:'p', y:'q'}
  ];

// if you want to check if x:'p' exists in arr
var check = arr.filter(function (elm){
    if (elm.x == 'p')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// or y:'q' exists in arr
var check = arr.filter(function (elm){
    if (elm.y == 'q')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// if you want to check, if the entire object {x:'p', y:'q'} exists in arr
var check = arr.filter(function (elm){
    if (elm.x == 'p' && elm.y == 'q')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// in all cases
console.log(check.length); // returns 1

if (check.length > 0)
{
   // returns true
   // object exists in array
   //write some codes
}

其他回答

Use:

function isInArray(array, search)
{
    return array.indexOf(search) >= 0;
}

// Usage
if(isInArray(my_array, "my_value"))
{
    //...
}

有几种方法可以找到答案。您可以使用内置的Array方法。最常用的是数组查找方法。

const arr1 = [1, 2, 3, 4, 5]
const result = arr1.find(ele => ele === 4)
console.log(result) //4

const result2 = arr1.find(ele => ele === 6)
console.log(result2) //undefined
/* 
If the element is present inside the array
then it will return the first element that
satisfies the given condition. Otherwise
undefined will return.
*/

如果您正在重复检查数组中是否存在对象,您可能应该查看

通过在数组中执行插入排序(将新对象放在正确的位置),始终保持数组排序将更新对象设置为删除+排序插入操作和在contains(a,obj)中使用二进制搜索查找。

它有一个参数:对象的数组数。数组中的每个对象都有两个由x和y表示的整数财产。该函数必须返回数组中满足numbers.x==numbers.y的所有此类对象的计数

var数=〔{x:1,y:1},{x:2,y:3},{x:3,y:3},{x:3,y:4},{x:4,y:5}];变量计数=0;var n=数字长度;对于(变量i=0;i<n;i++){如果(数字[i].x==数字[i].y){count+=1;}}警报(计数);

字面意思:

(使用Firefox v3.6,如前所述,带有for in注意事项(然而,下面的用法可能支持中的这一目的!即,枚举通过属性索引实际存在的数组元素(尤其是,数组长度属性未在for in属性列表中枚举!)。)

(拖放以下完整URI以进行即时模式浏览器测试。)

JavaScript:

  function ObjInRA(ra){var has=false; for(i in ra){has=true; break;} return has;}

  function check(ra){
      return ['There is ',ObjInRA(ra)?'an':'NO',' object in [',ra,'].'].join('')
  }
  alert([
            check([{}]), check([]), check([,2,3]),
            check(['']), '\t (a null string)', check([,,,])
        ].join('\n'));

其显示:

There is an object in [[object Object]].
There is NO object in [].
There is an object in [,2,3].
There is an object in [].
     (a null string)
There is NO object in [,,].

皱纹:如果要查找“特定”对象,请考虑:

JavaScript:警报({}!={});警报({}!=={});

因此:

JavaScript:

 obj = {prop:"value"}; 
 ra1 = [obj]; 
 ra2 = [{prop:"value"}];
 alert(ra1[0] == obj); 
 alert(ra2[0] == obj);

ra2通常被认为“包含”obj作为文本实体{prop:“value”}。

一个非常粗糙、简单、幼稚的解决方案(如代码需要增强资格):

JavaScript:

  obj={prop:"value"};   ra2=[{prop:"value"}];
  alert(
    ra2 . toSource() . indexOf( obj.toSource().match(/^.(.*).$/)[1] ) != -1 ?
      'found' :
      'missing' );

请参阅ref:在JavaScript数组中搜索对象。