代码之家  ›  专栏  ›  技术社区  ›  Surjeet Bhadauriya

javascript-获取arrow函数中元素的索引

  •  -3
  • Surjeet Bhadauriya  · 技术社区  · 8 年前

    如何在arrow函数中获取元素的索引?

    这是我的代码:

      this.data.forEach(element => {
        //console.log(index); //I want to get this index
          console.log(element);
      });
    

    有可能吗?

    2 回复  |  直到 8 年前
        1
  •  8
  •   Get Off My Lawn    8 年前

    可以通过向数组函数添加另一个参数来获取索引,

    this.data.forEach((element, index) = > {
      console.log(index); //I want to get this index
      console.log(element);
    });
    
        2
  •  3
  •   Sajeetharan    8 年前

    如果您的目的只是获取索引,则可以不使用foreach直接获取索引,

    console.log(this.data.findIndex(elem => elem === element));
    

    或者使用.foreach,可以从第二个参数获取索引

    this.data.forEach((element, index) = > {
      console.log(index); 
    });