javascript模拟php函数in_array
js中判断某个元素是否存在于某个js数组中,相当于php语言中的in_array函数。
Array.prototype.S=String.fromCharCode(2); Array.prototype.in_array=function(e){ varr=newRegExp(this.S+e+this.S); return(r.test(this.S+this.join(this.S)+this.S)); };
用法如下:
vararr=newArray(["b",2,"a",4,"test"]); arr.in_array('test');//判断test字符串是否存在于arr数组中,存在返回true否则false,此处将返回true
注:此函数只对字符和数字有效
jQuery中有类似的函数:http://docs.jquery.com/Utilities/jQuery.inArray
它的代码如下:
functioninArray(needle,haystack){ varlength=haystack.length; for(vari=0;i<length;i++){ if(haystack[i]==needle)returntrue; } returnfalse; }
以上就是本文给大家分享的全部内容了,希望大家能够喜欢。