问题
I am right now experimenting with the iterable destructuring expression, and i am wondering why a specific way does not work. Maybe you can help me on that.
For example that works:
var x, y, myIterable = [];
myIterable[Symbol.iterator] = function* () {
var count = 0;
while(count < 2){
yield count++;
}
};
var myArray = Array.from(myIterable);
console.log(([x,y] = myArray) === myArray);
//OUTPUT: true
But if i try it this way it returns false, can you explain why?
var x, y, myIterable = [];
myIterable[Symbol.iterator] = function* () {
var count = 0;
while(count < 2){
yield count++;
}
};
var myArray = Array.from(myIterable);
[x, y] = myArray;
console.log([x,y] === myArray);
//OUTPUT: false
回答1:
=== compares objects by references, since myArray and [x, y] evaluate to a different array.
[] === []; // false
{} === {}; // false
回答2:
Notwithstanding the === performs a reference equality check, per Benjamin's answer, the reason your first test returns true is because the result of the assignment:
[x, y] = myArray
is not [x, y], but is instead myArray - the assignment operator evaluates to the RHS, not the newly assigned LHS.
So given:
([x,y] = myArray) === myArray
the LHS of the === evaluates to myArray which is exactly the same object as you have on the RHS, so the result is true.
来源:https://stackoverflow.com/questions/34250302/ecmascript-2015-iterable-destructuring-expression