使用赋值解构交换术语将无法在函数内使用

时间:2018-07-12 14:22:33

标签: javascript ecmascript-6

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);

我在这里想念什么?

2 个答案:

答案 0 :(得分:1)

完成时

let a = 'alpha', b = 'beta';
[a,b] = [b,a];

您要交换ab的值。

完成时

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)

您正在不被“导出”变量的范围内进行交换。

在第一个示例中,您将在定义它们的范围内对实际变量ab进行操作。

但是,在第二个示例中,您正在对变量xy进行操作,它们与cd的值相同,但不是实际值cd因为它们是原始元素,所以不受箭头功能范围限制的cd

{
  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}`);
}