Array traversal (iteration) method

Iterative (traversal) method

We know the following 5 traversal methods, namely forEach(), map(), filter(), some(), every()

forEach() method: The forEach() method executes the given function once for each element of the array.

var arr = [10,20,30];
arr.forEach(function(value,index,array){
    
    
	console.log('数组元素' + value);
    console.log('数组元素的索引号' + index);
    console.log('数组本身' + array);
})

When called, three parameters can be passed in to the callback function in sequence:
1. The value of the current item in the array
2. The index of the current item in the array (optional)
3. The array object itself (optional)

The results show
Insert image description here
the map() method: The map() method creates a new array, which is composed of the return value of calling the provided function once for each element in the original array.

Similarities and differences between map() and forEach() methods
The output results of map() and forEach() are the same, but map() will allocate memory space to store a new array and return it, while forEach() will not return data; forEach() allows callback changes the elements of the original array.

Because map generates a new array, using map when you don't intend to use the returned new array goes against the original design intention. Please use forEach or for-of instead.

filter() method: The filter() method creates a new array containing all elements of the test implemented by the provided function.

var arr=[12,33,5,88,2,4,5456,234];
var newArr = arr.filter(function(value,index,array){
    
    
    return value%2 === 0;
});
console.log(newArr);

When called, three parameters are passed to the callback function:
1. The value of the element
2. The index of the element
3. The array itself being traversed

The results show
Insert image description here
the some() method: The some() method tests whether at least 1 element in the array passes the provided function test. It returns a Boolean value.
every() method: The every() method tests whether all elements in an array can pass the test of a specified function. It returns a boolean value.

filter(), some(), and every() are very similar. They all search whether the elements in the array meet the conditions of the callback function. However, filter() returns a new array, while some() and every() What is returned is a Boolean type value.

Guess you like

Origin blog.csdn.net/qq_48439911/article/details/124283500