The difference between traversal and iteration in es6 is: traversal emphasizes taking out the entire data in sequence, accessing all elements of the data structure; while iteration also takes out data in sequence, it does not guarantee how much it will take. , there is no guarantee that all the data will be fetched, it is a form of traversal.
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
What is iteration
Continuously retrieve data from a data set in a certain order The process
encapsulates the iterative process, usually an object. Different languages show different forms of iteration
What is traversal
Enables the members of the data structure to be arranged in a certain order;
ES6 creates a new traversal command for...of loop, and the Iterator interface is mainly used for for...of consumption (the object traversed by for of must have a traverser Interface can only be traversed)
Difference
Traversal is to access all elements of the data structure, and iteration is a form of traversal.
Iteration emphasizes that fetching data in sequence does not guarantee how much data will be retrieved, nor does it guarantee that all the data will be fetched
Convenience emphasizes that the entire data must be fetched in sequence
Examples are as follows:
Traverse a common array:
//遍历一个普通数组 const arr = [1,2,3,4,5]; for(let i = 0;i< arr.length;i++){ console.log(arr[i]) }
Iterate a common array:
//迭代一个数组 const iterator = { //用于迭代数组的对象 i : 0, next(){ var result = { // value : ? // done : ? value : arr[this.i], done : this.i >= arr.length } this.i ++; return result; } } console.log(iterator) //这个对象就为迭代器 //附加的功能 //让迭代器自己取数据,知道没有数据为止 let data = iterator.next(); while(!data.done){ console.log(data.value) data = iterator.next(); } console.log("迭代完成") //
[Related recommendations: javascript video tutorial、web front-end】
The above is the detailed content of What is the difference between traversal and iteration in es6. For more information, please follow other related articles on the PHP Chinese website!