其他分享
首页 > 其他分享> > ES6中的spread 扩展运算符

ES6中的spread 扩展运算符

作者:互联网

spread操作符(...)

1.数组使用扩展运算符

例子1:

let a = [1,2];
let b = ['a','b'];
let c = a.concat(b);//老写法
console.log(c);//[1,2,'a','b]
//新写法  在数组里面能扩展的值是可迭代的
let d = [...a,...b];
console.log(d);//[1,2,'a','b]

例子2:

let s = 'hello word';
s.split(');//[...s] 拆分[ "h", "e", "l", "l", "o", " ", "w", "o", "r", "l","d"]
console.log([1,2,...s,3,4]);[1, 2, "h", "e", "l", "l", "o", " ", "w", "o", "r", "l","d", 3, 4]

例子3:把类数组的对象转为数组

//老写法
let ps = Array.prototype.slice.call(document.querySelectorAll('p'));
console.log(ps);//[p,p,p,p]
//新写法
let p2 = [...document.querySelectorAll('p')];
console.log(ps2);//[p,p,p,p]

2.对对象使用扩展运算符

例子1:

var a = {x:1,y:2};
var copy = {};
//老写法
for(var key in a){
    copy[key] = a[key];  
}
console.log(copy);//{x:1,y:2}
//新写法
let copy2 = {...a};
console.log(copy2);//{x:1,y:2}

例子2:

var obj1 = {x:1,y:2,z:3};
var obj2 = {type:'cat',age:1,z:'abc'};
//老写法
var m = Obeject.assign({},obj1,obj2);
console.log(m);//{x: 1, y: 2, z: "abc", type: "cat", age: 1}
//新写法
let m2 = {x:100,...obj1,...obj2,y:200};
console.log(m2);//x: 1, y: 2, z: "abc", type: "cat", age: 1}

例子3:动态key

var x = 'type';
//老写法
var video = {
   src:'1.mp4',
   x:1
};
vide[x] = 2;
console.log(video);//{src:'1.mp4',x:1,type:2}
//新写法
let video2 = {
   src:'1.mp4',
   [x]:'动漫'
}
console.log(video2);//{src:'1.mp4',type:'动漫'}

 

标签:ES6,console,log,...,运算符,spread,let,var,写法
来源: https://www.cnblogs.com/chenhuaiyou/p/15243701.html