Home  >  Article  >  Web Front-end  >  javascript检查某个元素在数组中的索引值_javascript技巧

javascript检查某个元素在数组中的索引值_javascript技巧

WBOY
WBOYOriginal
2016-05-16 15:07:211184browse

在现在代浏览器中判断一个元素在不在一个数组中,咱们可以用Array对象的indexOf()方法来取得这个元素在当前数组中的索引值,若索引值不等于-1,数组中就存在这个元素,

例如:

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

下面咱们就来检测一下各个浏览器的兼容性,代码如下:

var arr = [2,53,23,'test',9,'array'];
if(!Array.indexOf){
  Array.prototype.indexOf = function(el){
 for (var i=0,n=this.length; i

上面就是用Array的indexOf方法来判断数组中一个元素是否存在的方法。

Array的原生方法:

concat(): 连接两个或更多的数组哦
join(): 把数组的所有元素放在一个字符串中
pop():删除并返回数组的最后一个元素
push():向数组的末尾添加一个元素,并返回数组长度。
reverse():颠倒数组中的元素顺序
shift(): 删除并返回数组的第一个元素。
slice():返回已选定的元素
sort():对数组的元素进行排序
splice():删除元素,并向数组添加新元素。
toSource():返回该对象的源代码
toString():把数组转换为字符串,并返回结果
valueOf():返回数组对象的原始值。

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