To determine whether an element is in an array in modern browsers, we can use the indexOf() method of the Array object to obtain the index value of the element in the current array. If the index value is not equal to -1, the index value in the array This element exists,
For example:
var arr = [2,53,23,'test',9,'array']; //判断array在不在数组arr中 arr.indexOf('array') !== -1 ? alert('存在') : alert('不存在'); 但是IE9以前的版本都不支持此方法,那咱们就只能扩展一个: 代码如下复制代码 Array.prototype.indexOf = function(el){ for (var i=0,n=this.length; i<n; i++){ if (this[i] === el){ return i; } } return -1; }
Let’s 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('存在') : alert('不存在');
The above is how to use Array’s indexOf method to determine whether an element in the array exists.
Array’s native method:
concat(): Concatenate two or more arrays
join(): Put all elements of the array into 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 array length.
reverse(): Reverse the order of elements in the array
shift(): Removes and returns the first element of the array.
slice(): Returns the selected element
sort(): Sort the elements of the array
splice(): removes elements and adds new elements to the array.
toSource(): Returns the source code of the object
toString(): Convert the array to a string and return the result
valueOf(): Returns the original value of the array object.