检查元素是否存在于数组中 [英] Check if an element is present in an array

查看:46
本文介绍了检查元素是否存在于数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在用来检查的函数如下:

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.

推荐答案

ECMAScript 2016 包含一个 includes() 数组方法专门解决了该问题,因此现在是首选方法.>

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(1, 2);  // false (second parameter is the index position in this array at which to begin searching)

截至 2018 年 7 月,此已在几乎所有主要浏览器,如果您需要支持旧浏览器polyfill 可用.

As of JULY 2018, this has been implemented in almost all major browsers, if you need to support an older browser a polyfill is available.

请注意,如果数组中的项目是对象,则返回 false.这是因为相似的对象在 JavaScript 中是两个不同的对象.

Note that this returns false if the item in the array is an object. This is because similar objects are two different objects in JavaScript.

这篇关于检查元素是否存在于数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆