Home > Web Front-end > JS Tutorial > body text

JavaScript checks the index value of an element in an array_javascript tips

WBOY
Release: 2016-05-16 15:07:21
Original
1281 people have browsed it

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;
}
Copy after login

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 &#63; alert('存在') : alert('不存在');
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!