检查数组中是否存在元素[重复]

本文翻译自:Check if an element is present in an array [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

The function I am using now to check this is the following: 我现在用来检查这个功能如下:

function inArray(needle,haystack)
{
    var count=haystack.length;
    for(var i=0;i<count;i++)
    {
        if(haystack[i]===needle){return true;}
    }
    return false;
}

It works. 有用。 What I'm looking for is whether there is a better way of doing this. 我正在寻找的是,是否有更好的方法来做到这一点。


#1楼

参考:https://stackoom.com/question/UxPg/检查数组中是否存在元素-重复


#2楼

Code: 码:

function isInArray(value, array) {
  return array.indexOf(value) > -1;
}

Execution: 执行:

isInArray(1, [1,2,3]); // true

Update (2017): 更新(2017年):

In modern browsers which follow the ECMAScript 2016 (ES7) standard, you can use the function Array.prototype.includes , which makes it way more easier to check if an item is present in an array: 在遵循ECMAScript 2016(ES7)标准的现代浏览器中,您可以使用函数Array.prototype.includes ,这样可以更容易地检查数组中是否存在项:

 const array = [1, 2, 3]; const value = 1; const isInArray = array.includes(value); console.log(isInArray); // true 


#3楼

You can use the _contains function from the underscore.js library to achieve this: 您可以使用underscore.js库中的_contains函数来实现此目的:

if (_.contains(haystack, needle)) {
  console.log("Needle found.");
};

#4楼

In lodash you can use _.includes (which also aliases to _.contains) 在lodash中你可以使用_.includes (它也是_.contains的别名)

You can search the whole array: 您可以搜索整个数组:

_.includes([1, 2, 3], 1); // true

You can search the array from a starting index: 您可以从起始索引搜索数组:

_.includes([1, 2, 3], 1, 1);  // false (begins search at index 1)

Search a string: 搜索字符串:

_.includes('pebbles', 'eb');  // true (string contains eb)

Also works for checking simple arrays of objects: 也适用于检查简单的对象数组:

_.includes({ 'user': 'fred', 'age': 40 }, 'fred');    // true
_.includes({ 'user': 'fred', 'age': false }, false);  // true

One thing to note about the last case is it works for primitives like strings, numbers and booleans but cannot search through arrays or objects 关于最后一种情况需要注意的一点是它适用于字符串,数字和布尔等基元,但不能搜索数组或对象

_.includes({ 'user': 'fred', 'age': {} }, {});   // false
_.includes({ 'user': [1,2,3], 'age': {} }, 3);   // false

#5楼

Depending on the size of the needle you're looking for the Array.filter might be useful. 根据您正在寻找的针的大小, Array.filter可能会有用。 Here's an example: 这是一个例子:

let filtered, arr = ['Haystack', 'Needle'];
filtered = arr.filter((elem) => {
  return elem.toLowerCase() === 'needle';
});
// filtered => ['needle']

#6楼

单行代码..将返回true或false

!!(arr.indexOf("val")+1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值