is to determine whether an element exists in the array of functions, since the JS string has indexof function, why not in the array object set a function like this, in fact, with indexof this idea is very good, do not know the development of JS Standard is based on what to consider, Such a common function is not taken into account.
JS to determine whether an element exists in a JS array, equivalent to the PHP language in the In_array function.
?
1 2 3 4 5 |
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:
?
1 2 |
var arr=new Array (["B", 2, "a", 4, "Test"]); Arr.in_array (' test ')//Determines whether the test string exists in the ARR array, returns true otherwise false, and returns true here |
Note: This function is valid only for characters and numbers
There are similar functions in jquery: Http://docs.jquery.com/Utilities/jQuery.inArray
Its code is as follows:
?
1 2 3 4 5 6 7 |
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 the article to share all the content, I hope you can enjoy.