let a = 'alpha', b = 'beta';
[a,b] = [b,a];
这将按预期交换a和b的值;
但是当放置在函数中时它不起作用
let c = 'charlie', d = 'delta';
swapVar = (x,y) => [x,y] = [y,x]
swapVar(c,d);
我在这里想念什么?
最佳答案
当你做
let a = 'alpha', b = 'beta';
[a,b] = [b,a];
您正在交换
a
和b
的值。当你做
let c = 'charlie', d = 'delta';
swapVar = (x,y) => {
// x and y are separate variables scoped within this block
[x,y] = [y,x]
console.log(x,y); // it is swapped alright but isn't reflected on c and d
c = x;
d = y;
// Now the value will have been reflected.
}
swapVar(c,d);
因此,在函数内部交换了值,但未在外部反映出来。您可以这样修改程序:
swapVar = (x,y) => [y,x]
[c, d] = swapVar(c, d); // now you're reflecting the swapped values on the outside
达到预期的效果