ES6 解构数组
// 在设计Javascript时,很明显遗漏了数组复制功能。而在ES5中,开发者使用concat()来克隆数组
var colors = ["red", "blue", "pink"];
var cloneColors = colors.concat();
console.log(cloneColors); // ["red", "blue", "pink"]
console.log(Object.is(colors, cloneColors)); // false
// concat()方法设计初衷是连接两个数组,如果调用时不传递参数则返回当前数组的副本
var colors2 = ["black", "green"];
console.log(colors.concat(colors2)); // ["red", "blue", "pink", "black", "green"]
// ES6 克隆数组
let [...cloneArray] = colors;
console.log(cloneColors) // ["red", "blue", "pink"]
// 可以混合使用对象解构和数组解构来创建更多的复杂的表达式
// 6.混合解构
let node = {
type: "json",
age: 1,
loc: {
start: {
line: "solid",
column: 20
},
end: {
line: "double",
column: 21
},
range: [0, 3]
}
};
let {loc: {range: [startIndex]}} = node;
console.log(startIndex); // 0
let {
loc: {start},
loc: {
range: [index]
}
} = node;
console.log(start.line); // solid
console.log(index); // 0
// 7.解构参数
function setCookie(name, value, options){
options = options || {};
let secure = options.secure,
path = options.path,
domain = options.domain,
expires = options.expires;
// 设置cookie代码
}
// name,value是必须的, 函数的声明部分,无法辨识函数的预期函数,必须通过阅读函数体才可以确定具体参数的情况
setCookie("type","js", {
secure: true,
expires: 700
});
/*
function setName(name,options) {
let {secure,path,domain,expires} = options;
console.log(name);
}
// Cannot destructure property `secure` of 'undefined' or 'null'
// 如果解构函数赋值表达式的右值为null和undefined,则程序会报错
setName("zhangsan",null);
setName("zhangsan");
*/
// 8.解构参数的默认值
const defaultParam = {
secure : false,
path : "/",
domain : "example.com",
expires : new Date(Date.now() + 360000000)
}
function setName(name,
{
secure = defaultParam.secure,
path = defaultParam.path,
domain = defaultParam.domain,
expires = defaultParam.expires
} = defaultParam
) {
console.log(name);
console.log(expires);
}
setName("admin"); // admin
// Mon Jun 24 2019 22:03:22 GMT+0800 (中国标准时间)
评论 (0)