JavaScript checks the index value of an element in an array _javascript tips

Source: Internet
Author: User

In the current generation of browsers to judge an element in not an array, we can use the Array object 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:

var arr = [2,53,23, ' Test ', 9, ' array '];
To determine that array is not in array arr
arr.indexof (' array ')!==-1 alert (' Presence '): alert (' nonexistent ');
However, the previous version of IE9 does not support this method, so we can only extend one: The
 code is copied as follows
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:

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 array:

Concat (): Connecting two or more arrays Oh
Join (): Put all the elements of an array in a string
Pop (): Delete and return 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.