[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)
var array = [0,1,2,3,4,5,6,7,8,9];
var result = 0;
var start = new Date().getTime();
for(var i = 0; i < 10000000; i++)
{
if(array.includes("test") === true){ result++; }
}
console.log(new Date().getTime() - start);
~1050 ms, indexOf
var array = [0,1,2,3,4,5,6,7,8,9];
var result = 0;
var start = new Date().getTime();
for(var i = 0; i < 10000000; i++)
{
if(array.indexOf("test") > -1){ result++; }
}
console.log(new Date().getTime() - start);
~650 ms,自定义功能
function inArray(target, array)
{
/* Caching array.length doesn't increase the performance of the for loop on V8 (and probably on most of other major engines) */
for(var i = 0; i < array.length; i++)
{
if(array[i] === target)
{
return true;
}
}
return false;
}
var array = [0,1,2,3,4,5,6,7,8,9];
var result = 0;
var start = new Date().getTime();
for(var i = 0; i < 10000000; i++)
{
if(inArray("test", array) === true){ result++; }
}
console.log(new Date().getTime() - start);
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
执行:
isInArray(1, [1,2,3]); // true
我建议您使用以下代码:
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle)
return true;
}
return false;
}