扩展运算符(...)的八种用法

2021-04-07  本文已影响0人  落墨诗卷

1.复制数组(浅拷贝)

const arr1 = [1,2,3];

const arr2 = [...arr1];

console.log(arr2);

// [ 1, 2, 3 ]

2.合并数组

const arr1 = [1,2,3];

const arr2 = [4,5,6];

const arr3 = [...arr1, ...arr2];

console.log(arr3);

// [ 1, 2, 3, 4, 5, 6 ]

3.向对象添加属性

const output = {...user, age: 31};

4.使用 Math() 函数

const arr1 = [1, -1, 0, 5, 3];

const min = Math.min(...arr1);

console.log(min);

// -1

5.rest 参数

const myFunc = (x1, x2, x3) => {

  console.log(x1);

  console.log(x2);

  console.log(x3);

};

const arr1 = [1, 2, 3];

myFunc(...arr1);

// 1

// 2

// 3

6.向函数传递无限参数

const myFunc = (...args) => {

  console.log(args);

};

7.解构对象

const {firstname, ...rest} = user;

console.log(firstname);

console.log(rest);

// 'Chris'

// { lastname: 'Bongers', age: 31 }

8.展开字符串

const str = 'Hello';

const arr = [...str];

console.log(arr);

// [ 'H', 'e', 'l', 'l', 'o' ]
上一篇下一篇

猜你喜欢

热点阅读