There are a lot of functions that provide data in js, but I have not been able to implement the method I want for a long time, later, I found that you can use the indexOf function to find and locate the index values of array elements. For more information, see.
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:
The Code is as follows: |
Copy code |
Var arr = [2, 53, 23, 'test', 9, 'array']; // Determine if the array is not in the array arr 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 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; } |
The following code checks the compatibility of various browsers:
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 ('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.