How does [b] [b = a, 0] exchange between a and b?

As gdoron noted,

var a = "a"; var b = "b"; a = [b][b = a,0]; 

A and b will change, and although it looks a bit hacky, it has aroused my curiosity, and I am very curious how this works. That makes no sense to me.

+6
source share
2 answers
 var a = "a"; var b = "b"; a = [b][b = a, 0]; 

Let me break the last line into pieces:

 [b] // Puts b in an array - a safe place for the swap. [b = a] // Assign a in b [b = a,0] // Assign a in b and return the later expression - 0 with the comma operator. 

so finally, this is a =[b][0] - the first object in the array [b] => b assigned to a

Live demo

read @am not I comment on this question:
When is the comma operator useful?
This is his code ...

+7
source

This can help (or prevent) thinking about these terms from a semantically equivalent lambda construct (here, parameter c replaces element 0):

 a = (function(c) { b = a; return c; })(b); 
+1
source

Source: https://habr.com/ru/post/911620/


All Articles