最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ecmascript 6 - Javascript - Get index of element in arrow function - Stack Overflow

programmeradmin5浏览0评论

How can I get the index of an element in Arrow Function?

Here is my code:

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

Is it possible?

How can I get the index of an element in Arrow Function?

Here is my code:

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

Is it possible?

Share Improve this question edited Jul 3, 2018 at 21:43 Barmar 782k56 gold badges545 silver badges659 bronze badges asked Jul 3, 2018 at 21:16 Surjeet BhadauriyaSurjeet Bhadauriya 7,1563 gold badges39 silver badges54 bronze badges 10
  • 1 forEach has several parameters, the second is the index. – ASDFGerte Commented Jul 3, 2018 at 21:17
  • This is not a question about angular or angularjs. Please stop adding those tags. – mhodges Commented Jul 3, 2018 at 21:22
  • "Angularjs is a JavaScript Language"? What are you babbling about? Angularjs is not a language it is a framework and as such this question has nothing to do with it. – gforce301 Commented Jul 3, 2018 at 21:27
  • 2 @SurjeetBhadauriya angularjs is not a language - it is a framework. Your question is about how the parameters to .forEach() work, which is specific to JavaScript. It has nothing to do with the angularjs framework. By that logic, you should also tag React, Backbone, Vue, etc. That is not the purpose of tags. – mhodges Commented Jul 3, 2018 at 21:27
  • 1 @bambam Haha true! – mhodges Commented Jul 3, 2018 at 21:35
 |  Show 5 more ments

2 Answers 2

Reset to default 12

you can get index by adding another parameter to array function,

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

You can directly get the index without using forEach if your purpose is just to get index,

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

or with .forEach, you can get the index from the second parameter

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

评论列表(0)

  1. 暂无评论