大话西游666
不,它没有一个。因此,大多数流行的库在其实用程序包中都附带一个库。查看jQuery的inArray和Prototype的Array.indexOf的示例。jQuery的实现就像您期望的那样简单:function inArray(needle, haystack) { var length = haystack.length; for(var i = 0; i < length; i++) { if(haystack[i] == needle) return true; } return false;}如果您要处理大量的数组元素,那么上面的技巧就可以很好地解决问题。编辑:哎呀。我什至没有注意到您想查看一个数组是否在另一个数组中。根据PHP文档,这是PHP的预期行为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克里斯和亚历克斯发布的代码不遵循此行为。Alex是Prototype的indexOf的正式版本,而Chris的更像是PHP的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请注意,我故意不扩展Array原型,因为这样做通常是一个坏主意。