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
orangularjs
. 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 theangularjs
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
2 Answers
Reset to default 12you 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);
});