Front-end tips: What are the ways to traverse the array?

The front-end development provides us with the concept of an array. A lot of data can be stored in an array, but when we need to find the data inside, we need to traverse the array. So what are the ways to traverse the array?

One. for loop

The length property is a very special property. When you see an array, everyone will think of length. What are its specific characteristics?

1. An array is a set of data, and the length attribute represents the number of contents in this array. Abbreviated as the length of the array.

2. The array object has no methods, only a unique property length.

3. When setting the property, it means to modify the length of the array. The length of the array will change.

4. When reading, it will return the current length of the array in real time.

for loop to achieve array traversal



1. Construct a subscript by for, and extract specific elements according to the subscript

2.(Variable name.length) can dynamically detect the number of array elements

3. arr[i] represents the number, not a counter, but an array element

4. arr.length means there are several, which is the length of the array


The forEach() function traverses the array from beginning to end. There are three parameters: the array element, the index of the element, and the array itself (if it is a parameter, it is the array element, which is the value of the array.


Output result:


It can be seen that:

1.val represents the value in the array, and key represents the subscript of the corresponding array

2. The method is used to call each element of the array and pass the element to the callback function, no return value

Three, map ()

The map method is to process the original array item by item in a loop, and return the new array without changing the value of the original array


Output result:



1. Return a new array, but do not change the original array

2. The map method has a return value, and the return value is received with a variable.

Four, for of to traverse the array

es6 adds a new for of loop to get the element



Different for the forEach method, it can be used in conjunction with break, continue and return

Provides a unified operation interface for traversing all data structures


for of cannot traverse objects.

This article is from Qianfeng Education , please indicate the source for reprinting.

Guess you like