在 JavaScript 中,有一种方式可以比较一个数组中的值,并查看它是否在另一个数组中。
类似于 PHP 的 in_array 函数吗?
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
in_array
的预期行为:$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}
if (in_array('o', $a)) {
echo "'o' was found\n";
}
// Output:
// 'ph' was found
// 'o' was found
array_intersect
。这就是你想要的:function arrayCompare(a1, a2) {
if (a1.length != a2.length) return false;
var length = a2.length;
for (var i = 0; i < length; i++) {
if (a1[i] !== a2[i]) return false;
}
return true;
}
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(typeof haystack[i] == 'object') {
if(arrayCompare(haystack[i], needle)) return true;
} else {
if(haystack[i] == needle) return true;
}
}
return false;
}
我来测试一下上面的内容:
var a = [['p','h'],['p','r'],'o'];
if(inArray(['p','h'], a)) {
alert('ph was found');
}
if(inArray(['f','i'], a)) {
alert('fi was found');
}
if(inArray('o', a)) {
alert('o was found');
}
// Results:
// alerts 'ph' was found
// alerts 'o' was found
jQuery.inArray()
不返回布尔值。它返回找到的元素的索引,如果未找到则返回-1。 - Brad KentindexOf
的文档 http://www.w3schools.com/jsref/jsref_indexof_array.asp - yussan现在有了Array.prototype.includes
方法:
includes() 方法用于判断一个数组是否包含一个指定的值,如果是返回 true,否则false。
var a = [1, 2, 3];
a.includes(2); // true
a.includes(4); // false
语法
arr.includes(searchElement)
arr.includes(searchElement, fromIndex)
Array.indexOf
是在 JavaScript 1.6 中引入的,但不被旧版浏览器所支持。幸好 Mozilla 的开发人员已经为您做了所有的艰苦工作,并且为您提供了此兼容性解决方案:
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;
};
}
甚至有一些方便的使用代码片段供你的脚本使用。
this.length >>> 0
的目的是什么?这是将其转换为数字类型吗? - hartoArray.indexOf
现在已经被ECMAScript第五版标准化,因此应该被认为是正确的“本地”方法。尽管如此,您仍需要嗅探并为旧的浏览器提供这个备用方法很长一段时间。@harto: 是的,它将 this.length
转换为一个可以表示为32位无符号整数的数字。本地的 Array
只能具有已经符合此规定的长度,但是规范说明您可以在不是 Array
的本地JS对象上调用 Array.prototype
方法。这和其他严谨的参数检查内容都是为了保证绝对符合规范。 - bobincePHP方式:
if (in_array('a', ['a', 'b', 'c'])) {
// do something if true
}
我的JavaScript解决方案:
if (['a', 'b', 'c'].includes('a')) {
// do something if true
}
let myArray = ['Kevin', 'Bob', 'Stuart'];
if( myArray.includes('Kevin'))
console.log('Kevin is here');
如果索引不是按顺序排列的,或者索引不是连续的,那么在这里列出的其他解决方案中的代码将会出现错误。一个效果可能更好的解决方案可能是:
function in_array(needle, haystack) {
for(var i in haystack) {
if(haystack[i] == needle) return true;
}
return false;
}
另外作为奖励,这里是与PHP的array_search相当的函数(用于在数组中查找元素的键):
function array_search(needle, haystack) {
for(var i in haystack) {
if(haystack[i] == needle) return i;
}
return false;
}
有一个名为 Locutus 的项目,它在 Javascript 中实现了 PHP 函数,其中包括 in_array(),您可以像在 PHP 中一样使用它。
使用示例:
in_array('van', myArray);
in_array(1, otherArray, true); // Forcing strict type
jQuery提供了解决方案,可以在此处查看文档: http://api.jquery.com/jquery.inarray/
$.inArray( 10, [ 8, 9, 10, 11 ] );
var a = [1,2,3,4,5,6,7,8,9];
var isSixInArray = a.filter(function(item){return item==6}).length ? true : false;
var isSixInArray = a.indexOf(6)>=0;
有一个等效的函数:
includes()
var a = [1, 2, 3]; a.includes(2); // true
的意思是检查数字 2 是否在数组[1, 2, 3]
中,如果是则返回true
。 - WEBjuju