Javascript 检查数组是否包含给定元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8240371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if array contains given element
提问by haynar
I have an array of numbers and dynamically adding new numbers to that array in for loop. But I need to avoid adding values that already exist in array. Is there a JS native way to check the presence of some value in array without doing 2nd nested loop. I don't want to use nested loop because the size of array may vary up to 10000
我有一个数字数组,并在 for 循环中向该数组动态添加新数字。但是我需要避免添加数组中已经存在的值。是否有一种 JS 本机方法来检查数组中某个值的存在,而无需执行第二个嵌套循环。我不想使用嵌套循环,因为数组的大小可能高达 10000
回答by SyraKozZ
Just use includes
.
只需使用includes
.
var array1 = [1, 2, 3];
console.log(array1.includes(2)); // true
回答by David Hu
You can use JavaScript's native Array.prototype.indexOf
, supported in most browsers: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
您可以使用 JavaScript 的 native Array.prototype.indexOf
,大多数浏览器都支持:https: //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
var a = [1, 2, 3];
console.log(a.indexOf(4)); // -1
indexOf
is faster than a for-loop but the algorithmic complexity is still O(n^2)
. If the size of the array gets much larger, consider a different data structure such as a hash table.
indexOf
比 for 循环快,但算法复杂度仍然是O(n^2)
。如果数组的大小变得更大,请考虑使用不同的数据结构,例如哈希表。
回答by nnnnnn
You can easily avoid a for loop by using a while loop. [Pause for laughter...] But seriously, even the built-in Array.indexOf()
method (supported by most browsers) probably uses a loop internally.
您可以使用 while 循环轻松避免 for 循环。[停顿一下……] 但是说真的,即使是内置Array.indexOf()
方法(大多数浏览器都支持)也可能在内部使用循环。
You could use a plain object instead, and add each number to the object as a property, then afterwards take the values from the object and put them in an actual array (or just use them in the object if that is convenient). Then you only have to loop through the "up to 10000" numbers once at the end:
您可以改用普通对象,并将每个数字作为属性添加到对象中,然后从对象中获取值并将它们放入实际数组中(或者如果方便,只需在对象中使用它们)。然后你只需要在最后循环一次“最多 10000”个数字:
var numbersObj = {},
numbersArray = [];
// your existing for statement here
for (var i=0; i<something; i++) {
var currentNumber = somethingElse(); // whatever your existing code is to
// determine the number to add goes here
// put the number in the object (as a key)
numersObj[currentNumber] = true;
}
// copy numbers out of object into array
for (var k in numbersObj)
if (numbersObj.hasOwnProperty(k))
numbersArray.push(k);
After which numbersArray
contains unique numbers only. The if test with .hasOwnProperty()
is "optional" depending on your point of view.
之后仅numbersArray
包含唯一编号。.hasOwnProperty()
根据您的观点,if 测试是“可选的”。
Within the first loop you could check if numbersObj
already holds the currentNumber
:
在第一个循环中,您可以检查是否numbersObj
已经拥有currentNumber
:
if (!numbersObj[currentNumber])
numbersObj[currentNumber] = true;
Or just (over)write it every time like I did in the first code block.
或者像我在第一个代码块中所做的那样,每次都(覆盖)写入它。
回答by Selvakumar Ponnusamy
try this,
尝试这个,
function eleContainsInArray(arr,element){
if(arr != null && arr.length >0){
for(var i=0;i<arr.length;i++){
if(arr[i] == element)
return true;
}
}
return false;
}
回答by Nicola Peluchetti
There is Array.indexOfwhich is supported from some browser, you can use this snippets of code to support all browser
有一些浏览器支持Array.indexOf,你可以使用这段代码来支持所有浏览器
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}