A, JQuery
If you are using JQuery, you can use the inArray() function:
Jquery inarray() function
Jquery.inarray (value,array) determines the position of the first argument in the array(-1 if none is found). determine the index of the first parameter in the array (-1 if not found). Returned value jquery parameter value (any) : used to search for array (array) : array to be processed.Copy the code
Usage:
$.inArray(value, array)
Copy the code
Write your own function
function contains(arr, obj) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) {
return true; }}return false;
}
Copy the code
Usage:
var arr = new Array(1.2.3);
contains(arr, 2);/ / return true
contains(arr, 4);/ / returns false
Copy the code
Add a function to Array
Array.prototype.contains = function (obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true; }}return false;
}
Copy the code
Usage:
[1.2.3].contains(2); / / return true
[1.2.3].contains('2'); / / returns false
Copy the code
The problem with indexOf, however, is that indexOf is not compatible with some versions of IE. 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) {
returni; }}return -1; }}Copy the code
Check whether an Array has an indexOf method. If not, extend the method. So the above code should precede the code using indexOf:
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) {
returni; }}return -1; }}var index = arr.indexOf('1');// Assign 0 to index
Copy the code