Home >Web Front-end >JS Tutorial >JS implementation code to determine whether an element is within an array_javascript skills
1. JQuery
If you are using JQuery, you can use the inArray() function:
Detailed explanation of jquery inarray() function
jquery.inarray(value,array)
Determines the position of the first argument in the array (returns -1 if not found).
determine the index of the first parameter in the array (-1 if not found).
Return value
jquery
Parameters
value (any): used to find whether
exists in the array
array (array): Array to be processed.
Usage:
2. Write your own functions
function contains(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) { return true; } } return false; }
Usage:
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; }
How to use:
4. Use indexOf
But there is a problem 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 Array has an indexOf method, and if not, extend this method.
So the above code 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');//为index赋值为0