Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS version of Ruby's .each_with_index

What is a method (or combination of methods) in Javascript that will iterate over the elements of an array and, aside operating on the elements of the array, will also allow me to use the index number of the current element?

In ruby this would equate to something like this:

array.each_with_index{ |element,index| element.method(index) }
like image 777
Franz Avatar asked Oct 31 '15 12:10

Franz


1 Answers

For arrays([1, 2, 3]) you can use .forEach

array.forEach(function (element, index) {

});

for Objects ({a: 1, b: 2, c: 3}) you can use .forEach with combination Object.keys

Object.keys(obj).forEach(function (key) {
   var value = obj[key];
});
like image 88
Oleksandr T. Avatar answered Nov 04 '22 08:11

Oleksandr T.