首页 > 解决方案 > 作为参数发送的变量更改父函数中的值

问题描述

最近我遇到了一个奇怪的问题。我知道在 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 不同,所以我必须说我很困惑。

有什么办法可以防止这种情况吗?还有为什么会这样?

标签: javascript

解决方案


推荐阅读