javascript - 作为参数发送的变量更改父函数中的值
问题描述
最近我遇到了一个奇怪的问题。我知道在 C++ 中有一种方法可以将变量作为参数发送给函数,并由被调用函数更改它们而不必返回它。
好吧,在 JS 中,我知道除非变量是全局变量,否则这是不可能的。然而确实如此。在我所做的一些测试中,这不应该是一件事,但特别是我的代码会发生这种情况。
const setState = (boatShore, boat, state) => {
// this shit should not perform a transition
console.log(JSON.stringify(state))
var valid = validateTransition(boatShore, boat, state)
console.log(JSON.stringify(state)) // the state here is different from the state at line 3.
console.log('\n');
boat = [];
boatShore = boatShore === 0 ? 1 : 0;
return { boatShore, boat, state, valid };
}
// this indeed changes the state in its runtime but it should not affect the caller
function validateTransition(boatShore, boat, state) {
if (boat.length > 2 || boat.length < 1) { return false }
for (let individual of boat) {
if (boatShore !== state[individual.pairIndex][individual.index]) return false;
}
state = transitionState(boat,state)
for (let pair of state) {
if (pair[0] !== pair[1]) {
for (let pairCheck of state) {
if (pairCheck[0] === pair[1]) {
return false;
}
}
}
}
return true;
}
function transitionState(boat,state) {
for (let individual of boat) {
if (state[individual.pairIndex][individual.index] === 0) {
state[individual.pairIndex][individual.index] = 1;
} else {
state[individual.pairIndex][individual.index] = 0;
}
}
return state;
}
problem(4);
function problem(n){
var state = []; //[[0,0], [0,0], [0,0], [0,0]]
var boat = []; //[{ pairIndex: 0, index: 0 },{ pairIndex: 0, index:1 }]
var boatShore = 0;
for (var i = 0; i < n; i++) {
state.push([0, 0]);
}
setState(boatShore, [{ pairIndex: 0, index: 0 },{ pairIndex: 0, index:1 }], state)
}
在这里,我有一个应该能够更改“状态”变量的函数。为了验证,我制作了一个单独的函数,通过它的检查还必须检查修改后的状态。在 setState 中,我只运行了验证转换的函数,并没有对状态进行任何实际更改。然而,第 3 行的 state 值与第 5 行的 state 不同,所以我必须说我很困惑。
有什么办法可以防止这种情况吗?还有为什么会这样?
解决方案
推荐阅读
- git - 'git diff' 的简写是什么,如果有的话?
- database - 如何创建从 SQL Server DB 到 MongoDB 或 Cassandra 的数据管道?
- angular - Angular 从 7 更新到 8,我卡住了 angular-i18next
- ruby-on-rails - 如何使用嵌套的 json 对象创建 json 响应?
- python - 如果我通过 powershell 运行 Flask 应用程序时没有任何反应,我该如何运行它?
- r - tidyverse 中 case_when 语句的 RHS 问题
- r - R 将字符串向量与 seq_len 组合
- angular - Angular Jasmine 测试,带有保护解析器的路由的模拟解析器
- powershell - 在 power shell 中安装 Az 模块时出现“PackageManagement\Install-Package:访问云文件被拒绝”错误
- r - 识别列的值出现在同一列中而另一列的值发生变化的情况