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

for (let i = 0;   i < arr.length;  i++) {
 console.log(arr[i]);
 }

for-in

for(let index in arr){
console.log(arr[index]);
}

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-of

for (let item of arr) {
 console.log(item);
 }

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

forEach

arr.forEach((item, index) => {
 console.log(item);
 });

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

arr.map((item, index) => {
 console.log(item);
 });

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.

filter

arr.filter((item, index) => {
 console.log(item);
 });

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!

clipboard.png