JS determines whether an element exists in a JS array, which is equivalent to the in_array function in the PHP language.
Array.prototype.S=String.fromCharCode(2); Array.prototype.in_array=function(e){ var r=new RegExp(this.S+e+this.S); return (r.test(this.S+this.join(this.S)+this.S)); };
Usage is as follows:
var arr=new Array(["b",2,"a",4,"test"]); arr.in_array('test');//判断 test 字符串是否存在于 arr 数组中,存在返回true 否则false,此处将返回true
Note: This function is only valid for characters and numbers
There is a similar function in jQuery: http://docs.jquery.com/Utilities/jQuery.inArray
Its code is as follows:
function inArray(needle, haystack) { var length = haystack.length; for(var i = 0; i < length; i++) { if(haystack[i] == needle) return true; } return false; }
The above is all the content shared with you in this article, I hope you will like it.