当前位置:网站首页>JS common method collection

JS common method collection

2022-06-11 22:59:00 Grace icing

js A collection of common methods

reduce

reduce() Traverse the current array , And a built-in callback function , Get... By parameters pre cur Define initial values, etc , Return any value you want to return .
pre: Get previous round return Result
cur: Get the element currently being traversed

const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => { 
return previousValue + currentValue
},
  initialValue
);

console.log(sumWithInitial);
// expected output: 10
const arr = [
    {
        age: 12,
        sex: ' male ',
        name: ' Xiao Ming ',
    },
    {
        age: 10,
        sex: ' Woman ',
        name: ' Xiaohong ',
    },
    {
        age: 9,
        sex: ' Woman ',
        name: ' floret ',
    },
]
arr.reduce((prev, cur) => {
  return {
    ...prev,
    [` Student _${cur.name}`]: cur.sex,
  };
}, {})
// expected output:
{
     Student _ Xiao Ming : " male "
     Student _ Xiaohong : " Woman "
     Student _ floret : " Woman "
}

Official explanation
reduce Execute... For each element in the array in turn callback function

Accept four parameters :
accumulator Accumulator
currentValue Current value
currentIndex Current index
array Array

[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
  return accumulator + currentValue;
});

[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
    return accumulator + currentValue
}, 10)

tips: It's usually safer to provide initial values
Provided initialValue, From the index 0 Start . If not provided initialValue,reduce From the index 1 Where we started callback Method , Skip the first index .
If the array has only one element , And it didn't provide initialValue, Then this unique value will be returned and callback Will not be executed .

Look at a few others

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(a, b) {
    return a.concat(b);
  },
  []
);
// flattened is [0, 1, 2, 3, 4, 5]
var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(
    (accumulator, currentValue) => accumulator + currentValue.x
    ,initialValue
);

console.log(sum) // logs 6
原网站

版权声明
本文为[Grace icing]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011618128691.html

随机推荐