首页 > 解决方案 > 函数调用相互影响

问题描述

我不确定我现在是否很累,但由于某种原因,我无法理解这一点:

const A = new Set([1, 2, 3, 4, 5]);
const B = new Set([4, 5, 6, 7, 8]);
const C = new Set([9, 10]);

function exercise09(arg1, arg2) {
  var union = arg1;

  for (let elem of arg2) {
    union.add(elem);
  }

  console.log(union.size);
}

exercise09(A, A); // Should yield 5
exercise09(A, B); // Should yield 8
exercise09(A, C); // Should yield 7

如果我独立运行它们,我会得到正确的结果,但是当连续运行时它们会相互影响。

在第 2 次呼叫之后运行时,第 3 次呼叫给出 10 而不是 7。

“A”的值在第二次调用后更改为包含 8 个元素?

我不明白为什么函数调用会影响一个和另一个?

标签: javascript

解决方案


make a copy of set and then work on it. var union = new Set(arg1)


推荐阅读