Javascript simulation php function in_array
It is to determine whether an element exists in an Array function. Since string in js has an indexOf function, why not set such a function in an Array object, in fact, the idea of using indexOf is quite good. I don't know what to consider for setting JS standards. I didn't take such a common function into consideration.
Js determines whether an element exists in a js array, which is equivalent to the in_array function in php.
?
| 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 )); }; |
The usage is as follows:
?
| 1 2 |
Var arr = new Array (["B", 2, "a", 4, "test"]); Arr. in_array ('test'); // checks whether the test string exists in the arr array. If yes, true is returned. Otherwise, false is returned. true is returned here. |
Note: This function is only valid for characters and numbers.
JQuery has a similar function: http://docs.jquery.com/Utilities/jQuery.inArray
The 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 all the content shared in this article. I hope you will like it.