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

这是我知道的唯一方法:

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

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

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


当前回答

只是另一种选择

// 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脚本的行为,从而导致意外行为。

其他回答

使用lodash的一些功能。

它简洁、准确,并且具有强大的跨平台支持。

接受的答案甚至不符合要求。

要求:推荐最简洁有效的方法来确定JavaScript数组是否包含对象。

接受答案:

$.inArray({'b': 2}, [{'a': 1}, {'b': 2}])
> -1

我的建议:

_.some([{'a': 1}, {'b': 2}], {'b': 2})
> true

笔记:

$.inArray可以很好地确定标量数组中是否存在标量值。。。

$.inArray(2, [1,2])
> 1

…但这个问题显然需要一种有效的方法来确定数组中是否包含对象。

为了处理标量和对象,可以执行以下操作:

(_.isObject(item)) ? _.some(ary, item) : (_.indexOf(ary, item) > -1)

复杂性O(n/2)

您可以使用任何库函数,但我使用的是核心JavaScript。如果返回true,我们首先搜索中间的元素,否则我们同时从左到中和从右到中搜索数组中的元素。因此,它将具有O(n/2)复杂性。并且它将返回true或false,指示它是否存在

let isExist = (arr, element)=> {
  let index = -1;
  if ((arr.length % 2 != 0) && arr[(arr.length-1)/2]===element) {
    index = 1;
    return true;
  }
  for(let i=0; i<Math.ceil(arr.length-1/2); i++){
    if (arr[i]===element || (arr[arr.length-i]===element)) {
      index = i;
      break;
    }
  }
  return (index<0)? false : true;
}



let array = ['apple', 'ball', 'cat', 'dog', 'egg']

console.log(isExist(array, 'yellow'));
//Result false because yellow doesn't exist in array
console.log(isExist(array, 'cat'));
//Result true because yellow exist in array

原型是这样做的:

/**
 *  Array#indexOf(item[, offset = 0]) -> Number
 *  - item (?): A value that may or may not be in the array.
 *  - offset (Number): The number of initial items to skip before beginning the
 *      search.
 *
 *  Returns the position of the first occurrence of `item` within the array &mdash; or
 *  `-1` if `item` doesn't exist in the array.
**/
function indexOf(item, i) {
  i || (i = 0);
  var length = this.length;
  if (i < 0) i = length + i;
  for (; i < length; i++)
    if (this[i] === item) return i;
  return -1;
}

另请参见此处了解它们是如何连接的。

这个需求的简单解决方案是使用find()

如果您有以下对象数组,

var users = [{id: "101", name: "Choose one..."},
{id: "102", name: "shilpa"},
{id: "103", name: "anita"},
{id: "104", name: "admin"},
{id: "105", name: "user"}];

然后可以检查具有您的值的对象是否已存在:

let data = users.find(object => object['id'] === '104');

如果数据为空,则没有admin,否则它将返回现有对象,如:

{id: "104", name: "admin"}

然后,您可以在数组中找到该对象的索引,并使用以下代码替换该对象:

let indexToUpdate = users.indexOf(data);
let newObject = {id: "104", name: "customer"};
users[indexToUpdate] = newObject;//your new object
console.log(users);

您将获得如下值:

[{id: "101", name: "Choose one..."},
{id: "102", name: "shilpa"},
{id: "103", name: "anita"},
{id: "104", name: "customer"},
{id: "105", name: "user"}];

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

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