<script>
// 数组位置方法
// 以下方法可以接收两个参数(需要查找的元素,(可选)查找起点的索引值)
// 返回值为第一个找到的数据在数组的索引值,未找到返回-1
// indexOf: 从前至后查找
// lastIndexOf: 从后到前查找
var arrs = [4,3,1,5,4,1,2];
console.log(arrs);
// 以下为indexOf示例
console.log("以下为indexOf(1)结果");
console.log(arrs.indexOf(1)); // 2
// 以下为lastIndexOf示例
console.log("以下为lastIndexOf(1)结果");
console.log(arrs.lastIndexOf(1)); // 5
</script>

该文介绍了JavaScript数组的indexOf和lastIndexOf方法,这两个方法用于查找数组中特定元素的索引。indexOf从前往后搜索,返回第一个匹配项的索引;lastIndexOf则从后往前查找,返回最后匹配项的索引。示例代码展示了如何使用这两个方法在数组arrs中查找数字1的索引位置。
2万+

被折叠的 条评论
为什么被折叠?



