javascript - 函数调用相互影响
问题描述
我不确定我现在是否很累,但由于某种原因,我无法理解这一点:
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 个元素?
我不明白为什么函数调用会影响一个和另一个?
解决方案
make a copy of set and then work on it. var union = new Set(arg1)
推荐阅读
- java - 转换列表
到 Class... 获取声明的方法 - javascript - 滚动位置固定元素与非固定元素同步
- codemirror - CodeMirror 6 React 包装器?
- python - 有没有办法在整个 sqlite 表中用另一个值替换特定值?
- c# - How can I properly activate Windows authentication prompt in ASP.NET?
- java - Pyspark,执行者在执行连接时失去连接
- c# - 如何从 Oracle 数据库中的多个表中检索数据,创建数据表,然后将这些数据存储在 C# 中的类对象中?
- git - 分叉新的回购
- neo4j - 如何在 Neo4j Virtual Machine Enterprise 中安装和使用 Graph Data Science 和 APOC 库?
- python - 循环中的列表行为非常奇怪