变量的解构赋值
数组的解构赋值
基本方法
let a = 1; let b = 2; let c = 3; //es6 解构 let [a, b, c] = [1, 2, 3];只要模式相同就可以匹配
let [foo, [[bar], baz]] = [1, [[2], 3]]; foo // 1 bar // 2 baz // 3 let [ , , third] = ["foo", "bar", "baz"]; third // "baz" let [x, , y] = [1, 2, 3]; x // 1 y // 3 let [head, ...tail] = [1, 2, 3, 4]; head // 1 tail // [2, 3, 4] let [x, y, ...z] = ['a']; x // "a" y // undefined z // []有默认值的解构赋值
let [foo = true] = []; foo // true let [x, y = 'b'] = ['a']; // x='a', y='b' let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'只有当赋值为undefined时才会使用默认值,null时不会
let [x = 1] = [undefined]; x // 1 let [x = 1] = [null]; x // null默认值为表达时 只有用到时才会求值
function f() { console.log('aaa'); } let [x = f()] = [1]; //f()不执行对象解构赋值
对象的结构赋值
let { foo, bar } = { foo: "aaa", bar: "bbb" }; foo // "aaa" bar // "bbb" 属性名必须完全相同属性名不同的解构赋值
let { foo: baz } = { foo: "aaa", bar: "bbb" }; baz // "aaa" foo // error: foo is not defined嵌套赋值
let obj = { p: [ 'Hello', { y: 'World' } ] }; let { p, p: [x, { y }] } = obj; x // "Hello" y // "World" p // ["Hello", {y: "World"}]对于已经声明的变量 为了防止解析时当做一个代码块 必须在外面加上括号
// 正确的写法 let x; ({x} = {x: 1});字符串解析赋值
const [a, b, c, d, e] = 'hello'; a // "h" b // "e" c // "l" d // "l" e // "o"数值和布尔值的解析赋值
let {toString: s} = 123; s === Number.prototype.toString // true let {toString: s} = true; s === Boolean.prototype.toString // true函数参数的解构赋值
用法
function add([x, y]){ return x + y; } add([1, 2]); // 3 原传入一个数组 解构赋值为几个变量如果要对已经声明的变量进行解构赋值的话 要使用圆括号
[(b)] = [3]; // 正确 ({ p: (d) } = {}); // 正确 [(parseInt.prop)] = [3]; // 正确