1.结构赋值
变量声明并赋值时的解构
var foo = ["one", "two", "three"]; var [one, two, three] = foo; console.log(one); // "one" console.log(two); // "two" console.log(three); // "three"
变量先声明后赋值时的解构
var a, b; [a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2
默认值(为了防止从数组中取出一个值为undefined
的对象,可以在表达式左边的数组中为任意对象预设默认值)
var a, b; [a=5, b=7] = [1]; console.log(a); // 1 console.log(b); // 7
交换变量
var a = 1; var b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1
解析一个从函数返回的数组
function f() { return [1, 2]; } var a, b; [a, b] = f(); console.log(a); // 1 console.log(b); // 2
忽略某些返回值
function f() { return [1, 2, 3]; } var [a, , b] = f(); console.log(a); // 1 console.log(b); // 3 也可以忽略全部
[,,] = f();
将剩余数组赋值给一个变量
var [a, ...b] = [1, 2, 3]; console.log(a); // 1 console.log(b); // [2, 3]
注意:如果剩余元素右侧有逗号,会报异常
var [a, ...b,] = [1, 2, 3]; // SyntaxError: rest element may not have a trailing comma
解构对象
基本赋值
var o = {p: 42, q: true}; var {p, q} = o; console.log(p); // 42 console.log(q); // true
无声明赋值
var a, b; ({a, b} = {a: 1, b: 2});
注意:赋值语句周围的圆括号 ( ... )
在使用对象字面量无声明解构赋值时是必须的。
{a, b} = {a: 1, b: 2}
不是有效的独立语法,因为左边的 {a, b}
被认为是一个块而不是对象字面量。
然而,({a, b} = {a: 1, b: 2})
是有效的,正如 var {a, b} = {a: 1, b: 2}
你的 ( ... )
表达式之前需要有一个分号,否则它可能会被当成上一行中的函数执行。
给新的变量名赋值
var o = {p: 42, q: true}; var {p: foo, q: bar} = o; console.log(foo); // 42 console.log(bar); // true
默认值(变量可以先赋予默认值。当要提取的对象对应属性解析为 undefined,变量就被赋予默认值。)
var {a = 10, b = 5} = {a: 3}; console.log(a); // 3 console.log(b); // 5
给新的变量命名并提供默认值(一个属性可以同时 1)从一个对象解构,并分配给一个不同名称的变量 2)分配一个默认值,以防未解构的值是 undefined
。)
var {a:aa = 10, b:bb = 5} = {a: 3}; console.log(aa); // 3 console.log(bb); // 5
对象解构中的 Rest
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40} a; // 10 b; // 20 rest; // { c: 30, d: 40 }
从作为函数实参的对象中提取数据
function userId({id}) { return id; } function whois({displayName: displayName, fullName: {firstName: name}}){ console.log(displayName + " is " + name); } var user = { id: 42, displayName: "jdoe", fullName: { firstName: "John", lastName: "Doe" } }; console.log("userId: " + userId(user)); // "userId: 42" whois(user); // "jdoe is John"