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
355 views
in Technique[技术] by (71.8m points)

javascript - 如何检查数组是否在JavaScript中包含值?(How do I check if an array includes a value in JavaScript?)

What is the most concise and efficient way to find out if a JavaScript array contains a value?

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

This is the only way I know to do it:

(这是我知道的唯一方法:)

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

Is there a better and more concise way to accomplish this?

(有没有更好,更简洁的方法来实现这一目标?)

This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array?

(这与Stack Overflow问题密切相关。 在JavaScript数组中查找项目的最佳方法?)

which addresses finding objects in an array using indexOf .

(它解决了使用indexOf在数组中查找对象的问题。)

  ask by brad translate from so

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

1 Reply

0 votes
by (71.8m points)

Current browsers have Array#includes , which does exactly that, is widely supported , and has a polyfill for older browsers.

(当前的浏览器有Array#includes ,这正是这么做的, 得到广泛支持 ,并具有填充工具旧版本浏览器。)

> ['joe', 'jane', 'mary'].includes('jane');
true 

You can also use Array#indexOf , which is less direct, but doesn't require Polyfills for out of date browsers.

(您还可以使用Array#indexOf ,它不太直接,但对于过期的浏览器不需要Polyfills。)

jQuery offers $.inArray , which is functionally equivalent to Array#indexOf .

(jQuery提供$.inArray ,在功能上等效于Array#indexOf 。)

underscore.js , a JavaScript utility library, offers _.contains(list, value) , alias _.include(list, value) , both of which use indexOf internally if passed a JavaScript array.

(underscore.js是一个JavaScript实用程序库,提供_.contains(list, value)和别名_.include(list, value) ,如果传递了JavaScript数组,则两者都在内部使用indexOf 。)

Some other frameworks offer similar methods:

(其他一些框架提供了类似的方法:)

Notice that some frameworks implement this as a function, while others add the function to the array prototype.

(注意,有些框架将此功能实现为函数,而其他框架则将该函数添加到数组原型中。)


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

...