解构
es6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称之为解构
//对象的解构
const stu={
name:'shawn',
age:'20',
gender:'男'
}
const {name,age,gender}=stu
console.log(name,age,gender) //shawn 20 男
//对象作为函数参数解构
const stu={
name:'shawn',
age:'20',
gender:'男'
}
function stuInfo({name,age,gender}){
return `${name}的年龄是${age},性别是${gender}`;
}
console.log(stuInfo(stu)); //shawn的年龄是20,性别是男
//数组的解构
const names = ["Henry","Bucky","Emily"];
const [name1,name2,name3] = names;
console.log(name1,name2,name3);//Henry Bucky Emily
//返回数组个数
const {length} = names;
console.log(length); //3
扩展运算符...
作用是把数组或类数组对象展开成一系列用逗号隔开的值
const arr1 = [1,2,3]
const arr2 = [4,5,6]
const arr3=[...arr1,...arr2]
console.log(arr3) //[1, 2, 3, 4, 5, 6]
应用场景
//数组深拷贝
const arr2 = arr1;
const arr3 = [...arr1];
console.log(arr1===arr2); //true, 说明arr和arr2指向同一个数组
console.log(arr1===arr3); //false, 说明arr3和arr指向不同数组
//把一个数组插入另一个数组字面量
const arr = [1,2,3]
const arr1 = [...arr, 4, 5, 6];
console.log(arr1);//[1, 2, 3, 4, 5, 6]
//字符串转数组
var str = 'love';
var arr = [...str];
console.log(arr);//[ 'l', 'o', 'v', 'e' ]
rest参数...
作用与扩展运算符恰好相反,把逗号隔开的值序列组合成一个数组
//主要用于不定参数,所以ES6开始可以不再使用arguments对象
bar = function(one, ...unknow) {
console.log(one);
console.log(unknow);
}
bar(1, 2, 3, 4,5);
//1
//[ 2, 3, 4 ,5]