JS checks whether the elements are implemented in the array code, js Array
I. JQuery
If JQuery is used, you can use the inArray () function:
Jquery inarray () Functions
Jquery. inarray (value, array)
Determine the position of the first parameter in the array (-1 is returned if no value is found ).
Determine the index of the first parameter in the array (-1 if not found ).
Return Value
Jquery
Parameters
Value (any): used to search for existence in the array
Array (array): the array to be processed.
Usage:
Copy codeThe Code is as follows:
$. InArray (value, array)
Ii. Write Functions by yourself
function contains(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) { return true; } } return false;}
Usage:
Copy codeThe Code is as follows:
Var arr = new Array (1, 2, 3 );
Contains (arr, 2); // return true
Contains (arr, 4); // return false
3. Add a function to Array
Array.prototype.contains = function (obj) { var i = this.length; while (i--) { if (this[i] === obj) { return true; } } return false;}
Usage:
Copy codeThe Code is as follows:
[1, 2, 3]. contains (2); // return true
[1, 2, 3]. contains ('2'); // return false
4. Use indexOf
However, the problem is that IndexOf is incompatible in some IE versions. You can use the following method:
if (!Array.indexOf) { Array.prototype.indexOf = function (obj) { for (var i = 0; i < this.length; i++) { if (this[i] == obj) { return i; } } return -1; }}
First, determine whether the Array has the indexOf method. If not, extend this method.
Therefore, the code above should be written before the code using the indexOf method:
Var arr = new Array ('1', '2', '3'); if (! Array. indexOf) {Array. prototype. indexOf = function (obj) {for (var I = 0; I <this. length; I ++) {if (this [I] = obj) {return I ;}} return-1 ;}} var index = arr. indexOf ('1'); // value 0 for index