手写loadsh函数的第三天
<script>
// 定义一个数组
const array = [1, 2, 3, 4, 1, 2];
// 自定义函数 indexof,用于查找值在数组中的索引位置
// 参数 arr: 数组,value: 要查找的值,fromIndex: 开始查找的索引位置,默认为 0
function indexof(arr, value, fromIndex = 0) {
let index; // 存储找到的索引位置
for (let i = fromIndex; i < arr.length; i++) {
if (arr[i] == value) {
index = i; // 如果找到值,将索引位置赋值给 index
} else {
index = -1; // 如果未找到值,将 index 设为 -1
}
}
return index; // 返回找到的索引位置或 -1(未找到)
}
// 在数组 array 中从索引位置 3(包括索引 3)开始查找值 0
console.log(indexof(array, 0, 3));
</script>