Javascript Array.indexOf()方法
作者:--
发布时间:2019-11-20
评论:0
阅读:0
javascript数组indexof()方法返回在该给定元素可以数组中可以找到第一个索引,或如果它不存在返回-1。
语法
array.indexof(searchelement[, fromindex]);
下面是参数的详细信息:
返回值:
返回找到的元素的索引
兼容性:
这种方法是一个javascript扩展到ecma-262标准;因此它可能不存在在标准的其他实现。为了使它工作,你需要添加下面的脚本的顶部代码:
if (!array.prototype.indexof)
{
array.prototype.indexof = function(elt /*, from*/)
{
var len = this.length;
var from = number(arguments[1]) || 0;
from = (from < 0)
? math.ceil(from)
: math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
例子:
<html>
<head>
<title>javascript array indexof method</title>
</head>
<body>
<script type="text/javascript">
if (!array.prototype.indexof)
{
array.prototype.indexof = function(elt /*, from*/)
{
var len = this.length;
var from = number(arguments[1]) || 0;
from = (from < 0)
? math.ceil(from)
: math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
var index = [12, 5, 8, 130, 44].indexof(8);
document.write("index is : " + index );
var index = [12, 5, 8, 130, 44].indexof(13);
document.write("<br />index is : " + index );
</script>
</body>
</html>
这将产生以下结果:
index is : 2
index is : -1