The original

There was actually a previous article on closures, but since I’ve covered them in previous articles, closures have been shelved for now. Change the subject:

content

Higher-order function;

  • At least the following conditions must be met:
      1. Functions can be passed as arguments;
      1. The function can be output as a return value.

Common higher-order functions include Map, Reduce, Filter, and Sort.


1. Map

array.map(function(currentValue,index,arr), thisValue)

Map () does not change the original array

[55.44.66.11].map(function(currentValue,index,arr){
	console.log(currentValue); // The map() method processes the elements in their original order
	console.log(index);
	console.log(arr);
});
Copy the code

Let’s take an array and do some calculation to get a new array

var newArr = [55.44.66.11].map(function(item,index,arr){
	return item *10;
});
console.log(newArr);/ / [550, 440, 660, 110]
Copy the code

2. reduce

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

InitialValue: the initialValue passed to the function;

Let the front and back items in the array do some sort of calculation and add up the final value.

var newArr = [15.5.2.3.1.1.4.7].reduce(function(total,num){
	return total + Math.round(num);// Round the array elements and calculate the sum
}, 0);
console.log(newArr);/ / 24
Copy the code

Reduce () does not perform callbacks for empty arrays

3. filter

array.filter(function(currentValue,index,arr), thisValue)

Filter () does not change the original array

var newArr = [32.33.12.40].filter(function(item){
	return item > 32;
});
console.log(newArr);/ / [40] 33,
Copy the code

Filter out the items that meet the conditions to form a new array.

4. forEach

array.forEach(function(currentValue, index, arr), thisValue)

Map () is syntactically identical to forEach(), and can be done with ‘forEach()’ as well as with ‘map()’, but with a difference.

  • The difference between:
    • forEach()The return value isundefined, can not chain call;
    • map()Returns a new array, unchanged from the original array.

conclusion

Practice makes perfect and shortage in one, success depends on forethought and destroyed by.