本章只是個人的一個筆記,邊看邊記錄,怕自己混淆,特意記錄下的隨筆,如果有不一樣的見解,歡迎指點。
一、解構賦值只是數組和對象?
let a,b,c = 1,'hello',undefined
//Uncaught SyntaxError: Unexpected string
但是,我們可以這樣
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
如果對數值布爾型有疑惑可以看下
let ao = Number(124).toString();
console.log(ao); //"124"
let ab = Number(124).toString;
console.log(ab); //? toString() { [native code] }
函數
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
注意看下面兩組
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]
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]
第一組{x = 0, y = 0} = {}
是為函數move的參數指定默認值。
第二組{x, y} = { x: 0, y: 0 }
被視為一個對象,如下
function move () {
var _ref = arguments.length > 0 && arguments[0] !== undefined
? arguments[0]
:{x:0, y:0},
x = _ref.x,
y=_ref.y;
return [x, y];
}
二、在數組解構賦值過程中容易混淆的部分
正常情況下,我們一般這樣用
let [a, b, c] = [1, 2, 3];
a //1
b //2
c //3
默認值
let [foo = true] = [];
foo // true
對undefined
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
可以看到y的解構賦值是undefined,也就是解構賦值失敗,所以依然保持默認值'b'
三、在對象解構賦值過程中容易混淆的部分
正常的用法
let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
當變量名與屬性名不一致時
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
大括號不要當一行中的第一位
// 錯誤的寫法
let x;
{x} = {x: 1};
// SyntaxError: syntax error
這種情況{x}會被JavaScript引擎認為是一個代碼塊
// 正確的寫法
let x;
({x} = {x: 1});