The difference between forEach, map, every, some, filter

One, forEach (), used to traverse the array, no return value

Here an array is first given (the following examples are common):

var arr=[1,-2,3,4,-5];

Then all I have to do is double each item in the array

arr.forEach(function(item,index,array){
    array[index] = item * 2;
});
console.log(arr);   // [2,-4,6,8,-10]

According to the above, array[index] is equal to item

arr.forEach(function(item,index,array){
    console.log(array[index] === item);   // true
});

2. map(), used to traverse the array and return the new array after processing

var newArr = arr.map(function(item,index,array){
    return item * 2;
});
console.log(newArr);   // [2,-4,6,8,-10]

It can be seen that this method is similar to the function of forEach(), except that map() has a return value and will return a new array, so that the original array will not be affected after processing the array.

3. every(), used to judge whether each element in the array satisfies the condition, and returns a Boolean value

var isEvery = arr.every(function(item,index,array){
    return item > 0;
});
console.log(isEvery);   // false

It can be seen that the example is to judge whether the elements in the array arr are all positive numbers, but obviously not, so the method finally returns false.

4. some(), used to judge whether there is an element in the array that satisfies the condition, and returns a Boolean value

var isSome = arr.some(function(item,index,array){
    return item < 0;
});
console.log(isSome);   // true

It can be seen that this method is similar to every(). In the example, it is necessary to judge whether there are negative elements in the array arr, which obviously exists, so this method finally returns true.

5. filter(), used to filter the elements in the array that meet the conditions, and return a new filtered array

var minus = arr.filter(function(item,index,array){
    return item < 0;
});
console.log(minus);   // [-2, -5]

As you can see, the example is to filter out all negative numbers in the array arr, so this method finally returns a new filtered array [-2, -5].

 补充: 以上五大方法除了传递一个匿名函数作为参数之外,还可以传第二个参数,该参数用于指定匿名函数内的this指向,例如:

// 只传一个匿名函数
arr.forEach(function(item,index,array){
    console.log(this);  // window
})

// 传两个参数
arr.forEach(function(item,index,array){
    console.log(this);  // [1, -2, 3, 4, -5]
},arr);

Compatibility: Since the above methods are ES5+ methods, IE8 and below browsers are not compatible.

Summary

① forEach()无返回值,map()和filter()返回新数组,every()和some()返回布尔值
② 匿名函数中this指向默认为window,可通过传第二参数来更改之
③ 五种遍历方法均为ES5+方法

Guess you like

Origin blog.csdn.net/pidanl/article/details/128567759
Recommended