Method: 1. Use the "array.keys()" method, which can traverse the array index; 2. Use the "array.values()" method, which can traverse the array elements; 3. Use " Array.entries()" method, which can traverse the index and elements of the array.
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
ES6 provides the entries(), keys(), and values() methods to return the iterator of the array. For the iterator (Iterator), you can use for.. .of for convenience, or you can use the Iterator.next() method of the iterator returned by entries() to traverse.
1. Use keys() to traverse.
keys() returns a traverser of array element index numbers.
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'] for (let index of arr1.keys()) { console.log(index); }
Result:
You can see that the output is the index of each array element.
0 1 2 3 4 5 6 7 8 9 10
2. Use values() to traverse.
values() returns a traverser of array element values.
for (let val of arr1.values()) { console.log(val); }
Result:
a b c d e f g h i j k
3. Use entries() to traverse.
Used with destructuring, you can get the index and value of the element.
for (let [index, val] of arr1.entries()) { console.log(index, val); }
Result:
0 'a' 1 'b' 2 'c' 3 'd' 4 'e' 5 'f' 6 'g' 7 'h' 8 'i' 9 'j' 10 'k'
4. Use Iterator.next() to traverse.
Based on the traverser returned by entries(), calling the next() method of the traverser can obtain the access entry of each element. The entry has a done attribute to indicate whether it is convenient to end. You can get the value attribute through the entrance, which is the index of the element and the array of values.
let arrEntries=arr1.entries(); let entry=arrEntries.next(); while(!entry.done){ console.log(entry.value); entry=arrEntries.next(); }
Result:
[ 0, 'a' ] [ 1, 'b' ] [ 2, 'c' ] [ 3, 'd' ] [ 4, 'e' ] [ 5, 'f' ] [ 6, 'g' ] [ 7, 'h' ] [ 8, 'i' ] [ 9, 'j' ] [ 10, 'k' ]
[Related recommendations: javascript video tutorial, web front-end]
The above is the detailed content of How to implement array traversal in es6. For more information, please follow other related articles on the PHP Chinese website!