• 03-查找数组中某一项的索引(如果有重复的查找第一项)-for of如何得到索引


    方法一: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);
  • 相关阅读:
    MySQL 8.0+ 时区问题
    SSM框架整合搭建流程
    最大子段和、最大子矩阵和
    棋盘覆盖(分治)
    石子合并问题
    矩阵连乘
    selenium完成滑块验证
    背包问题(2)
    背包问题(1)
    皇后问题
  • 原文地址:https://www.cnblogs.com/haoqiyouyu/p/14891739.html
Copyright © 2020-2023  润新知