分享人: 江吉仪
目录
1.背景介绍
2.知识剖析
3.常见问题
4.解决方案
5.编码实战
6.扩展思考
7.参考文献
8.更多讨论
ECMAScript 6.0(以下简称 ES6)是 JavaScript 语言的下一代标准,已经在 2015 年 6 月正式发布了。 它的目标,是使得 JavaScript 语言可以用来编写复杂的大型应用程序,成为企业级开发语言。
下面是介绍下ES6中的解构赋值
ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。
let a = 1;
let b = 2;
let c = 3;
ES6允许写成这样:
let [a, b, c] = [1, 2, 3];
上面代码表示,可以从数组中提取值,按照对应位置,对变量赋值。
数组的解构,数组的元素是按次序排列的,变量的取值由它的位置决定 。
const color = ['red', 'blue']
const [first, second] = color
console.log(first) //'red'
console.log(second) //'blue'
const people = {
name: 'lux',
age: 20
}
const { name, age } = people
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f // 'hello'
l // 'world'
对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。真正被赋值的是后者,而不是前者。
解构不成功的值
当解构不成功值为undefined
var [a,b] = [1];
console.log(a,b); //1 undefined
var [a,b = 2] = [1];
console.log(a,b); //1 2
var [a,b = 2] = [1,null];
console.log(a,b); //1 null
let [a,b = a] = [1];
console.log(a,b); //1 1
let [a = b,b = 1] = [];
console.log(a,b); //Uncaught ReferenceError: b is not defined
let a = 1;
let b = 2;
[a,b] = [b,a];
console.log(a,b); //2 1
// 返回一个数组
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一个对象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();
let arr = [
{
title:1111,
love:{
one:'one_1',
two:'two_1'
}
},
{
title:2222,
love:{
one:'one_2',
two:'two_2'
}
}
];
for(let {title,love:{two}} of arr){
console.log(title,two);
}
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]
var name = `Your name is ${first} ${last}.`
var roadPoem = 'Then took the other, as just as fair,\n\t'
+ 'And having perhaps the better claim\n\t'
+ 'Because it was grassy and wanted wear,\n\t'
+ 'Though as for that the passing there\n\t'
+ 'Had worn them really about the same,\n\t'
解构赋值还有什么用法?
let {log,warn} = console;
log('hello');
console.log('hello')
1.新增块级作用域(只要在{}花括号内的代码块即可以认为 let 的作用域)
2.暂时性死区(使用let命令声明变量之前,该变量都是不可用的)
3.不存在变量提升(let 的作用域是在它所在当前代码块,但不会被提升到当前函数的最顶部)
4.不允许重复声明变量
感谢大家观看
制作人:高昕 | 江吉仪