Últimamente me he encontrado con un problema extraño. Sé que había en C++ una forma de enviar variables como parámetro a una función y cambiarlas por la función llamada sin tener que devolverla.
Bueno, en JS sabía que eso no sería posible a menos que la variable sea global. Sin embargo lo hace. En algunas pruebas que he hecho esto no debería ser una cosa, pero con mi código en particular esto sucede.
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) }Aquí tengo una función que debería poder cambiar la variable "estado". Para la validación, hice una función separada que a lo largo de sus controles también debe verificar el estado modificado. Dentro de setState ejecuté solo la función para validar la transición y no realicé ningún cambio real en el estado. Sin embargo, el valor del estado en la línea 3 es diferente en comparación con el estado en la línea 5, por lo que debo decir que estoy bastante confundido.
Hay alguna forma de prevenir esto ? Además, ¿por qué sucede esto?