方法一:for循环写法:最简单,拿到传入值在数组中第一次出现的索引
var arr = [1, 34, 21, 5, 2, 45, 15, 21, 24, 6]; function findIndex(arr, ele) { for (let i = 0; i < arr.length; i++) { if (arr[i] === ele) { return i; } } } console.log(findIndex(arr, 21))
方法二:forEach循环
forEach循环 找到传入的值在数组中的索引:但是输出的是最后一项的索引(重复值),因为其不发在循环体中return
var arr = [1, 34, 21, 5, 2, 45, 15, 21, 24, 6]; function searchEleIndex(arr, ele) { let index; arr.forEach((item, i) => { if (item === ele) { index = i; }; }) return index; } console.log(searchEleIndex(arr, 21));
方法三:for of 方法三是解决方法二的
var arr = [1, 34, 21, 5, 2, 45, 15, 21, 24, 6]; function searchArrEle(arr, ele) { // Set和Map都可以,目的都是为了能让for of遍历 // let mapArr = new Map(arr.map((x, i) => [i, x])); let mapArr = new Set(arr.map((x, i) => [i, x])); for (let [index, val] of mapArr) { if (val === ele) { return index; } } } let res = searchArrEle(arr, 21); console.log(res);