JS moving in variable that doesn’t have to move

Asked

Viewed 50 times

1

I made a code that groups some items closer in one, by position x and y. The code is doing correctly, but I am facing a problem. The first time the function runs, it does all process normally. When I click on a button to run again, it should take the array items PosicoesOriginal = [...] and play in another variable for this variable to be modified and not the PosicoesOriginal...

const PosicoesOriginal = [.....]; //Aqui tem todos os itens
function GeraPosicoesDistribuidores(){

       let grupos = [];

       //Aqui ele joga os itens dentro de outra variavel, pois não pode modificar o PosicoesOriginal

       let espelhoPosicoes = PosicoesOriginal;

       console.log(PosicoesOriginal);

       espelhoPosicoes.forEach(function(i, p){

        let toUp = i.y + distancia;
        let toDown = i.y - distancia;
        let toRight = i.x + distancia;
        let toLeft = i.x - distancia;
        let estado = i.estado;

          let gruposTemp = [];
          espelhoPosicoes.forEach(function(e, ps){

            if(between(e.y, toDown, toUp) && between(e.x, toLeft, toRight)){

              gruposTemp.push(e);
              espelhoPosicoes.splice(ps, 1);
            }
          });

          grupos.push(gruposTemp);
        });

        if(espelhoPosicoes != ''){

          espelhoPosicoes.forEach(function(e, p){
            let gruposTemp = [];

            gruposTemp.push(e);
            grupos.push(gruposTemp);
          });
        }

        console.log(PosicoesOriginal); //Verifico o que tem
        return grupos;
    }

In the first console log. it displays all the data correctly, at last console log. it displays fewer items, but the strange thing is that I did not put the splice to touch the PosicoesOriginal and yes in espelhoPosicoes. If I withdraw the splice It displays the same on 2 console.log

1 answer

0

PosicoesOriginal and espelhoPosicoes refer to the same object, that is, when espelhoPosicoes changes the object, changes are reflected in PosicoesOriginal. If it is necessary to change the value of one without changing the value of another one must copy the object.
Since the object is an Array, it can be copied as follows:

    espelhoPosicoes = PosicoesOriginal.slice()

See the documentation for MDN

Browser other questions tagged

You are not signed in. Login or sign up in order to post.