Javascript Array entries()

Introduction

Array entries() will return an iterator of index/value pairs.

array.entries()

Iterate with index and element

const a = ['a', 'b', 'c'];
for (const [index, element] of a.entries())
  console.log(index, element);//ww w.j av a2s.c  o m

Using a for-of loop

var a = ['a', 'b', 'c'];
var iterator = a.entries();

for (let e of iterator) {
  console.log(e);//from w  ww  .  j a v  a2s.c  o  m
}
const a = ["foo", "bar", "baz", "qux"];
const aEntries = Array.from(a.entries());
console.log(aEntries); // [[0, "foo"], [1, "bar"], [2, "baz"], [3, "qux"]]  

Use ES6 destructuring to split out the key/value pairs inside a loop:

const a = ["foo", "bar", "baz", "qux"];

for (const [idx, element] of a.entries()){
    console.log(idx); /*  w  w w  .  j  a  v  a2 s  .  co m*/
    console.log(element);
}



PreviousNext

Related