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);
我在这里想念什么?
答案 0 :(得分:1)
完成时
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
达到预期的效果。
答案 1 :(得分:0)
您正在不被“导出”变量的范围内进行交换。
在第一个示例中,您将在定义它们的范围内对实际变量a
和b
进行操作。
但是,在第二个示例中,您正在对变量x
和y
进行操作,它们与c
和d
的值相同,但不是实际值c
和d
因为它们是原始元素,所以不受箭头功能范围限制的c
和d
。
{
let a = 'alpha',
b = 'beta';
console.log("Test 1");
console.log(`before a: ${a} b: ${b}`);
[a, b] = [b, a];
console.log(`after a: ${a} b: ${b}`);
}
{
let c = 'charlie',
d = 'delta';
console.log("Test 2");
console.log(`before c: ${c} d: ${d}`);
swapVar = (x, y) => [x, y] = [y, x]
/*
function swapVarExpanded(x, y) {
const tmp = [y, x];
x = tmp[0];
y = tmp[1];
// Doesn't actually matter
// because x and y die at the next closing curly brace due to scope
}
*/
swapVar(c, d);
console.log(`after c: ${c} d: ${d}`);
}