Вопрос

Swap two numbers

C++:

int a = 3;
int b = 5;
a^=b^=a^=b;
printf("%d, %d\n", a, b); //5, 3

PHP:

$a = 3; $b = 5;
$a^=$b^=$a^=$b;
echo "$a, $b\n"; //5, 3

Javascript:

> a=3;b=5;a^=b^=a^=b;[a,b]
[ 0, 3 ]

Why? Looks like all variables initialized before all expression executed...

Это было полезно?

Решение

Your assignment in JS is equivalent to

a = a ^ (b = b ^ (a = a ^ b));

and that is evaluated from left to right and for a we get

3 ^ (5 ^ (3 ^ 5))

So an easy fix would be to write

a = (b ^= (a ^= b)) ^ a;

Welcome to the world of JS =)

Другие советы

In ES6, you can simply use destructing assignment:

var a = 3
var b = 5
[a, b] = [b, a]

which behaves as expected.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top