解构
对象解构
在想要声明一个变量并要引用另一个对象内同名值时使用
//原写法let language = study.language;//对象解构let { language } = study;
//多个let language = study.language;let algorithm = study.algorithm;//对象解构let { language,algorithm } = study;
复制代码
使用解构赋值,语法会更加清晰。如果变量和对象内值不同名值,可以使用别名的解构语法:
let { language:JS } = study;console.log(JS)//'language'
复制代码
注意:当解构的属性不存在时会得到 undefined,如果解构属性中嵌套属性的父对象是 undefined、null,会抛出异常。
数组解构
数组解构语法于对象解构语法类似:
const study = ["language", "algorithm"]; const [language, algorithm] = study; console.log(language);//'language'
复制代码
解构赋值时可以不需要的值,也可以设定默认值
//使用逗号间隔,就可以跳过不需要的值const study = ["language", "brush questions", "algorithm"];const [language, , algorithm] = study;console.log(algorithm); //'algorithm'
//设定默认值 const study = ["language", "brush questions", "algorithm"]; const [language, , algorithm="math"] = study; console.log(algorithm); //'math'
复制代码
在 ES5 中,当需要两个值的变量转换时,通常需要第三个临时变量。使用解构可以避免声明临时变量:
//原写法let language = study.language;let algorithm = study.algorithm;let aux = language;language = algorithm;algorithm = aux;
//ES6let language = study.language;let algorithm = study.algorithm;[language, algorithm] = [algorithm, language];
复制代码
函数参数的默认值
ES6 的函数参数也能默认值。所以箭头也可以设置默认值:
const study = (language = 1) => { language * 60;};// 可以为任何一个参数赋值function study(a = 1, b = 2, c = 3) { return a + b + c;}study(undefined, undefined, 4); //1+2+4=7
复制代码
在向函数传递多个 options 对象参数时,如果函数的使用者传入了一个 options 对象,则所有的默认值会失效:
const study = { noon: "algorithm", nignt: "brush questions", }; function study(options = study) { console.log(options.noon); console.log(options.nignt); } study(); // 'algorithm' // 'brush questions' // 传入options study({ nignt: "language", }); // undefined // 'language'
复制代码
可以结合解构解决该问题
函数参数的解构
与提供一个默认值相比,更好的方法是解构整个 options,并在解构模式中为每个属性指定默认值:
function study({ noon = "algorithm", nignt = "brush questions" }) { console.log(noon); console.log(nignt); } study({ nignt: "language", }); // 'algorithm' // 'language'
复制代码
但是使用该方法后,函数不传入 options,会导致默认值丢失,carFactory 会报错。可以为 options 添加一个空对象作为默认值避免该问题:
function study({ noon = "algorithm", nignt = "brush questions" }={}) {console.log(noon);console.log(nignt);} study(); // 'algorithm' // 'brush questions'
复制代码
评论