Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

javascript - 检查数组中是否存在元素[重复](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.

(我正在寻找的是,是否有更好的方法来做到这一点。)

  ask by Francisc translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ECMAScript 2016 incorporates an includes() method for arrays that specifically solves the problem, and so is now the preferred method.

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

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

(截至2018年7月,几乎所有主流浏览器都已实现 ,如果您需要支持IE,则可以使用polyfill)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...