ECMAScript 2015, iterable destructuring expression

倾然丶 夕夏残阳落幕 提交于 2019-12-10 16:40:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!