When I saw Ruan Yifeng’s ES6 tutorial on destructuring assignment and default values, I didn’t quite understand this place.
Original link
Note that ES6 uses the strict equality operator (===) internally to determine whether a position has a value. Therefore, if an array member is not strictly equal to undefined, the default value will not take effect.
function f() {
console.log('aaa');
}
let [x = f()] = [1];
The book says that the above code is equivalent to the following code
let x;
if ([1][0] === undefined) {
x = f();
} else {
x = [1][0];
}
May I ask where this [1][0]
comes from? Shouldn't it be like this?
let x;
if (1 === undefined) {
x = f();
} else {
x = 1;
}
学习ing2017-06-07 09:26:42
When deconstructing an array, the principle is as follows: put one or more variables into array A, and then make this array A equal to another array B. Then during destructuring, the value of a certain position in array A will be equal to the corresponding position of array B. value.
let [x = f()] = [1];
The meaning of this code is to first create an array A. The first item in array A is x, and then there is an array B, B = [1].
Then let A = B. The final effect is A[ 0] = B[0], that is, x=B[0]
, that is, x=[1][0]
.
So when judging whether it is equal to undefined, do this
if([1][0] === undefined)
PHP中文网2017-06-07 09:26:42
The 1 in [1] on the right corresponds to x, that is, [1][0]
corresponds to x
欧阳克2017-06-07 09:26:42
Deconstruct, deconstruct, deconstruct. . . So the purpose is to untie the things on the right side of the equal sign, so we must untie [1]
.
So let [x]=[1]
, then x
is [1][0]
, which is 1
. So in fact, the assignment of x
is judged based on [1][0]
.
I don’t know if I understand what I’m saying, but I’d better give you the documentation:
https://developer.mozilla.org...