js常用方法合集

reduce

reduce() 将当前数组进行遍历,并内置一个回调函数,通过参数获取 pre cur 定义初始值等,返回你所要返回的任意值。
pre: 获取上一轮return的结果
cur: 获取当前正在遍历的元素

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: '男',
        name: '小明',
    },
    {
        age: 10,
        sex: '女',
        name: '小红',
    },
    {
        age: 9,
        sex: '女',
        name: '小花',
    },
]
arr.reduce((prev, cur) => {
  return {
    ...prev,
    [`学生_${cur.name}`]: cur.sex,
  };
}, {})
// expected output:
{
    学生_小明: "男"
    学生_小红: "女"
    学生_小花: "女"
}

官方解释
reduce为数组中的每一个元素依次执行callback函数

接受四个参数:
accumulator 累计器
currentValue 当前值
currentIndex 当前索引
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: 提供初始值通常更安全
如果提供initialValue,从索引0开始。如果没有提供initialValue,reduce 会从索引1的地方开始执行 callback 方法,跳过第一个索引。
如果数组仅有一个元素,并且没有提供initialValue,那么此唯一值将被返回并且callback不会被执行。

再看几个其他🌰

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

assign

assign 接受两个参数,目标对象和源对象。如果目标对象中的属性具有相同的键,则属性将被源对象中的属性覆盖

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);
// source 只会拷贝源对象自身的并且可枚举的属性到目标对象
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(source)
// expected output: Object { b: 4, c: 5 }

tips: Object.assign 不会在那些source对象值为 null 或 undefined 的时候抛出错误


Grace糖衣
15 声望2 粉丝

用于记录一些平时遇到的问题


« 上一篇
vue原理初探
下一篇 »
聊一聊 iconfont