Javascript checks the index value of an element in the array, javascript Array

Source: Internet
Author: User
Tags javascript array

Javascript checks the index value of an element in the array, javascript Array

In the current browser, we can determine that an element is not in an Array. We can use the indexOf () method of the Array object to obtain the index value of this element in the current Array, if the index value is not equal to-1, this element exists in the array,

For example:

Var arr = [, 23, 'test', 9, 'array']; // determines whether the array is not in the array arr. indexOf ('array ')! =-1? Alert ('exist'): alert ('nonexistent '); however, earlier versions of IE9 do not support this method, so we can only expand one: the code below copies the code Array. prototype. indexOf = function (el) {for (var I = 0, n = this. length; I <n; I ++) {if (this [I] === el) {return I ;}} return-1 ;}

The following code checks the compatibility of various browsers:

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 ('exist'): alert ('nonexistent ');

The above method uses the indexOf method of Array to determine whether an element exists in the Array.

Native method of Array:

Concat (): connects two or more arrays.
Join (): Place all elements of the array in a string.
Pop (): deletes and returns the last element of the array.
Push (): Add an element to the end of the array and return the length of the array.
Reverse (): reverse the order of elements in the array
Shift (): delete and return the first element of the array.
Slice (): returns the selected Element
Sort (): sorts the elements of an array.
Splice (): delete an element and add a new element to the array.
ToSource (): returns the source code of the object.
ToString (): converts an array to a string and returns the result.
ValueOf (): returns the original value of the 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.