参数默认值:
ES6新增默认参数功能,参数可以有默认值(初始值),通常有默认值的写在最后
// 解构
let obj = {
host: "192.168.1.1",
username: "王一",
password: 123456,
}
function connect({ host, username, password, port = 3006 }) { //port=3006 设置参数默认值
console.log(host);
console.log(username);
console.log(password);
console.log(port);
}
connect(obj);
rest参数:
ES6无法获取arguments集合,rest参数来代替
// ...拓展运算符 rest参数来代替
function showName1(a, b, ...rest) { //把3,4,5 用[] 包住,变成数组
// console.log(a);
// console.log(b);
console.log(rest);
}
showName1(1, 2, 3, 4, 5); //Array(3)[3, 4, 5]
// arguments
function showName2(a, b, c) {
// console.log(a);
// console.log(b);
console.log(arguments);
}
showName2(1, 2, 3, 4, 5); //Arguments(5)[1, 2, 3, 4, 5]
… 拓展运算符 rest反作用:可以将 数组展开成,分割的参数列表
let arr = [1, 2, 3];
console.log(arr); //Array(3) [1, 2, 3]
console.log(...arr); // 1 2 3
//需要将数组转化为参数形式,传递到某个函数中
let goods = [4, 5, 6];
goods.push(...arr);
console.log(goods); //Array(6)[4, 5, 6, 1, 2, 3]
// 完美取代了apply
let max = Math.max(...goods);
console.log(max); //6
利用拓展运算符,结构数组 :
// 展开:
let arr = [1, 2, 3];
let goods = [...arr]; //拓展运算符展开
goods.push(4);
console.log(arr); //[1, 2, 3]
console.log(goods); //[1, 2, 3, 4]
// 合并:
let arr = [1, 2, 3];
let goods = [4, 5, 6];
let x = [...arr, ...goods]; //拓展运算符合并
console.log(arr); //[1, 2, 3]
console.log(goods); //[4, 5, 6]
console.log(x); //[1, 2, 3,4,5,6]
利用拓展运算符,解构对象:
let obj = {
a: 1,
b: 2,
c: 3,
d: 4
}
let { a, b, ...z } = obj;
console.log(a); //1
console.log(b); //2
console.log(z); //{c: 3, d: 4}
let n = {
...obj
}
console.log(n); //{a: 1, b: 2, c: 3, d: 4}