Home > Web Front-end > JS Tutorial > JS implementation code to determine whether an element is within an array_javascript skills

JS implementation code to determine whether an element is within an array_javascript skills

WBOY
Release: 2016-05-16 15:07:19
Original
2601 people have browsed it

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:

Copy code The code is as follows:

$.inArray(value, array)

2. Write your own functions

function contains(arr, obj) {
  var i = arr.length;
  while (i--) {
    if (arr[i] === obj) {
      return true;
    }
  }
  return false;
}
Copy after login

Usage:

Copy code The 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;
}
Copy after login

How to use:

Copy code The code is as follows:

[1, 2, 3].contains(2); //Return true
[1, 2, 3].contains('2'); //Return false

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;
  }
}
Copy after login

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
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template