This article will briefly talk about array traversal in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Using a for loop is the most common traversal method in an array.
The first return value is to traverse the array For each bit, the second bit of the return value can be regarded as the index value of the array. You can nest if statements in a for loop to judge element values and execute loop statements based on conditions.
2, use the forEach() method
a. How to use forEach():
The forEach method traverses the array from beginning to end, for each Element calls the specified function. The incoming parameter of the forEach method is a function. The function can pass in three parameters, which are, in order, array elements, element indexes and the array itself. It is not mandatory to pass in three parameters at the same time. You can pass in the number of parameters as needed.
Array[1,2,3,4] calls the forEach method and returns the parameter values in the passed parameter function. We can see that ele represents each element in the array. One bit, index represents the index value of the array, and arr represents the array calling this method.
Use the forEach method to implement the accumulation of array elements
b. Source code implementation of the forEach() method
Extend the custom myForEach method to the prototype of the array. Traverse according to the number of elements in the array, use each bit this[i] of the array and the representative array index i as function parameters, and execute the parameter fn function in the for loop. this represents the array in which the myForEach method is called.
3, use the map() method
The map() method passes each element of the called array to the specified function and returns an array containing the return value of the function. The original array is not changed. The use of map() method is the same as forEach() method.
Think about small connections:
Modify the data structure of the data and output it. Convert all elements of array arr into the form of the data structure of array b.
Answer:
Summary: The above is the entire content of this article. I hope it can be helpful to everyone’s study. helped. For more related tutorials, please visit JavaScript Video Tutorial!
Related recommendations:
The above is the detailed content of A brief discussion on array traversal in JavaScript. For more information, please follow other related articles on the PHP Chinese website!