All methods of traversal in Javascript

  array, Iterator, javascript, Traversal

In arraysconst arr = [1, 2, 3];For example, the following methods can be used for traversal operations:


for (let i = 0;   i < arr.length;  i++) {


for(let index in arr){

for-inActually, it traverses the enumerable attributes of an object, which is an unordered traversal, so it cannot be used when an orderly traversal of an array is required.for-in.


for (let item of arr) {

Any implementationIterative protocol(Iteration protocols)Objects of (Array, Map, Set, String, etc.) are availablefor-ofIteration.


arr.forEach((item, index) => {

HereforEachrefer toArray.prototype.forEach,forEachIs an array-specific method that cannot be used by other data structures. Of course, some data structures can also define their ownforEachMethods, such as bydocument.querySelectorAllAcquiredNodeListAlso have their ownforEachMethods, usage andarryTheforEachThe same, but they are not one thing.

map, index) => {

Note: map will return a new array with the same length as the element group. The elements in the new array are calculated by the element group elements.


arr.filter((item, index) => {

Note: filter will also return a new array, the new array length < = the original array length, and the elements in the new array will be filtered from the original array.

These are all the methods I can think of. If there are other methods, I hope to remind you!

Thank you for reading. In addition, I’m here to help my friends raise funds for love. I hope everyone can give some love. My friend’s mother is suffering from rectal cancer. She is currently receiving treatment in Beijing Armed Police General Hospital. Please leave a message and leave your contact information. Thank you in the future!