es6中...扩展运算符的使用

43 阅读1分钟

合并数组

//es5写法,使用concat
let arr1 = [1,2];
let arr2 = [5,6];
let newArr = [20];
newArr = newArr.concat(arr1).concat(arr2);
//es6写法
let arr1 = [1,2];
let arr2 = [5,6];
let newArr = [20];
newArr = [20,...arr1,...arr2];  

合并对象

const baseSquirtle = {
  name: 'Squirtle',
  type: 'Water'
};
 
const squirtleDetails = {
  species: 'Tiny Turtle Pokemon',
  evolution: 'Wartortle'
};
 
const squirtle = { ...baseSquirtle, ...squirtleDetails };
console.log(squirtle); 
//Result: { name: 'Squirtle', type: 'Water', species: 'Tiny Turtle Pokemon', evolution: 'Wartortle' }

为数组新增成员

const pokemon = ['小红', '小李'];
const charmander = '大大';
 
const pokedex = [...pokemon, charmander];
 
console.log(pokedex); 
 
//Result: [ '小红', '小李', '大大' ]

为对象新增属性

const aa= { name: '小红', type: '123' };
const obj= {
  ...aa,
  unit: '米',
  id: '1'
};
 
console.log(obj); 
 
//Result: { name: '小红', type: '123', unit: '米', id: '1' }

将一个数组添加到另一个数组的尾部:

let arr1 = [0, 1, 2];  
let arr2 = [3, 4, 5]; 
//es5写法
Array.prototype.push.apply(arr1, arr2); 
//es6写法
let arr1 = [0, 1, 2];  
let arr2 = [3, 4, 5];  
arr1.push(...arr2); 

将字符串转换成数组:

//es5写法需要splitjoin的操作
//...
//es6写法
[...'hello']  
// [ "h", "e", "l", "l", "o" ] 

解构赋值

let obj = {name:"小明",age:18,hobby:"小红"};
        let newobj  = {
            ...obj
        }
        console.log(newobj)//和obj一样