$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
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
function arrayIntersect(a, b) {
var intersection = [];
for(var i = 0; i < a.length; i++) {
if(inArray(b, a[i]))
intersection.push(a[i]);
}
return intersection;
}
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;
};
}
inArray: function(needle, haystack)
{
var result = false;
for (var i in haystack) {
if (haystack[i] === needle) {
result = true;
break;
}
}
return result;
}