How do these two variables exchange using the same string?

I don’t know how to learn demo 2 because it is difficult for me.

//demo1.js var a = 1; var b = 2; var c; c = b; b = a; a = c; log(a); // a = 2 log(b); // b = 1 I can read this one. //demo 2.js var a = 1, b = 2; a = [b][b = a, 0]; // why? '0' is a varible? console.log(a,b) //output a = 2, b =1 
+4
source share
2 answers
 // v---- 1. v---- 3. a = [b][b = a, 0]; // ^---^-- 2. 
  • Put the value of the variable b in a new array.

  • The next set of square brackets is the member statement used to get the index. In this case, this space is used to reassign the value of variable a variable b . This can be done because the original value of b safely in the array (from step 1).

  • Separated by a comma operator, then index 0 used as the actual value of the returned array, which, if you recall, is the original value of b . Then it is assigned a through first = assignment in the string.

So, to summarize, b is placed in an array and extracted using index 0 and assigned to a on the left, but not earlier than a assigned to b (borrowing the space of the member operator [] ).


This can also be written like this:

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

Now the only difference is that the second array index is used to complete the job. Probably a little clearer.

+2
source

Javascript's comma operator evaluates its left operand, discards it, and returns its right operand after evaluation. Its only use is when the left operand has a side effect (for example, changing the value of a variable), but you do not want its result.

[b] defines an array containing b.

[b = a, 0] evaluates b = a - so b now contains the value of a. Then he drops it. Then it takes an element at index 0 from [b] - returns b. a now contains the value of b that was written there, rather than the updated value of b, so our swap is successful (albeit confusing).

0
source

All Articles