Search code examples
javascriptenumerate

Javascript entries() not returning anything


I want to get the array elements, with their indexes, I use entries() as below but it does not print out anything, and it does not give any errors.

var array1 = ['a', 'b', 'c'];

var iterator1 = array1.entries();

for ([k, v] in iterator1) {
  console.log(k, v)
}


Solution

  • You should use for of instead of for in

    var array1 = ['a', 'b', 'c'];
    var iterator1 = array1.entries();
    
    for ([k, v] of iterator1) {
      console.log(k, v)
    }


    Another way is to use done property and next method of iterators

    var array1 = ['a', 'b', 'c'];
    var iterator1 = array1.entries();
    let result = iterator1.next()
    
    while (!result.done) {
      let [k, v] = result.value
      console.log(k, v)
      result = iterator1.next()
    }