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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…