解构赋值--字符串,数值和布尔值,函数参数,圆括号问题
一、字符串的解构赋值
字符串在解构赋值时,字符串会被转为一个类似数组的对象
const [a, b, c, d, e] = 'hello'; a // "h" b // "e" c // "l" d // "l" e // "o"
类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值
let {length : len} = 'hello';
len // 5
二、数值和布尔值的解构赋值
解构赋值时,等号右边是数值和布尔值,则会先转为对象
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
解构赋值的原则,只要等号右边的值不是对象或数组(字符串是类数组),就先将其转为对象。由于undefined和null无法转为对象,所以对他们进行解构赋值会报错
let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError
三、函数参数的解构赋值
function add([x, y]){ return x + y; } add([1, 2]); // 3
[[1, 2], [3, 4]].map(([a, b]) => a + b); // [ 3, 7 ]
默认值:
function move({x = 0, y = 0} = {}) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, 0] move({}); // [0, 0] move(); // [0, 0]
上面代码中,函数move的参数是一个对象,通过对这个对象进行解构,得到变量x和y的值。如果解构失败,x和y等于默认值
但:
function move({x, y} = { x: 0, y: 0 }) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, undefined] move({}); // [undefined, undefined] move(); // [0, 0]
上面代码是为函数move的参数指定默认值,而不是为变量x和y指定默认值,所以会得到与前一种写法不同的结果。
undefined就会触发函数参数的默认值
[1, undefined, 3].map((x = 'yes') => x); // [ 1, 'yes', 3 ]
四、圆括号问题
可以使用圆括号的只有一种情况:赋值语句的非模式部分可以使用圆括号
[(b)] = [3]; // 正确 ({ p: (d) } = {}); // 正确 [(parseInt.prop)] = [3]; // 正确
以上三局都可以正确执行
1.他们都是赋值语句,而不是声明语句
2.他们的圆括号都不属于模式的一部分·
不可以使用圆括号的情况:
1.变量声明语句
// 全部报错 let [(a)] = [1]; let {x: (c)} = {}; let ({x: c}) = {}; let {(x: c)} = {}; let {(x): c} = {}; let { o: ({ p: p }) } = { o: { p: 2 } };
2.函数参数,函数参数也属于变量声明嘛
// 报错 function f([(z)]) { return z; } // 报错 function f([z,(x)]) { return x; }
3.赋值语句的模式
// 全部报错 ({ p: a }) = { p: 42 }; ([a]) = [5];
[(b)] = [3]; // 正确 ({ p: (d) } = {}); // 正确 // 正确的写法 let x; ({x} = {x: 1});
浙公网安备 33010602011771号