JavaScript array.indexOf()方法返回可以在数组中找到给定元素的第一个索引,如果不存在,则返回-1。
array.indexOf(searchElement[, fromIndex]);
searchElement - 要在数组中定位的元素。
FromIndex - 开始搜索的索引。默认值为0,即将搜索整个数组。如果索引大于或等于数组的长度,则返回-1。
返回找到的元素的索引。
此方法是ECMA-262标准的JavaScript扩展;因此,它可能不存在于该标准的其他实现中。要使其工作,您需要在脚本顶部添加以下代码。
链接:https://www.learnfk.comhttps://www.learnfk.com/javascript/array-indexof.html
来源:LearnFk无涯教程网
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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)