获取某个元素第一次出现在数组(json数组)的索引

    function firstIndex(arr, text) {
      // 若元素不存在在数组中返回-1
      let firstVal = -1;
      for (let i = 0; i < arr.length; i++) {
        // json (arr[i].id == text)
        if (arr[i] === text) {
          firstVal = i;
          return firstVal;
          break;
        }
      }
      return firstVal;
    }
    // json数组
    // let array = [{ id: "1" }, { id: "2" }, { id: "3" }];
    // let text = "2";
    // 普通数组
    let array = [1, 2, 3, 4, 5];
    let text = 3;
    console.log("获取某个元素第一次出现在数组的索引", firstIndex(array, text));

猜你喜欢

转载自www.cnblogs.com/wyuan-yuan/p/9435957.html