JS checks the index value of an element in an array

Source: Internet
Author: User

In the current generation of browsers to judge an element in not an array, we can use the array object's IndexOf () method to obtain the index of the element in the present array, if the index value is not equal to-1, the array exists in this element, for example:

The code is as follows Copy Code

var arr = [2,53,23, ' Test ', 9, ' array '];

Judge array is not in array arr

Arr.indexof (' array ')!==-1? Alert (' existence '): alert (' nonexistent ');

But the previous version of IE9 does not support this method, so we can only extend one:

The code is as follows Copy Code

Array.prototype.indexOf = function (EL) {
for (var i=0,n=this.length; i<n; i++) {
if (this[i] = = EL) {
return i;
}
}
return-1;
}

Here we will check the compatibility of each browser, the code is as follows:

The code is as follows Copy Code

var arr = [2,53,23, ' Test ', 9, ' array '];
if (! Array.indexof) {
Array.prototype.indexOf = function (EL) {
for (var i=0,n=this.length; i<n; i++) {
if (this[i] = = EL) {
return i;
}
}
return-1;
}
}
Arr.indexof (' array ')!==-1? Alert (' existence '): alert (' nonexistent ');

The above is a method to determine whether an element exists in an array using the IndexOf method of array.

The native method of the array:
Concat ()   : Connecting two or more arrays Oh
Join (): Put all the elements of an array in a string
Pop (): Deletes and returns the last element of the array
push ( ): Adds an element to the end of the array and returns the length of the array.
Reverse (): Reverses the order of elements in an array
Shift (): Deletes and returns the first element of the array.
Slice (): Returns the selected element
sort (): Sorts the elements of an array
splice (): Deletes an element and adds a new element to the array.
Tosource (): Returns the source code for this object
ToString (): Converts an array to a string and returns the result
valueof (): Returns the original value of an array object.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.