简体   繁体   中英

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) } 

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() } 

To use index and element of an array, you can use the const [key, value] notation in conjunction with the of keyword, in order to use the iterator.

 const a = ['a', 'b', 'c']; for (const [index, element] of a.entries()) { console.log(index, element); } // 0 'a' // 1 'b' // 2 'c' 

You could also call next on the iterator directly.

 var array1 = ['a', 'b', 'c']; var iterator1 = array1.entries(); console.log(iterator1.next().value); // expected output: Array [0, "a"] console.log(iterator1.next().value); // expected output: Array [1, "b"] 

See also: Mozilla docs - Array.entries()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM