I have the code:
let linha = { quantidade: 1 };
let coluna = [];
coluna.push(linha);
coluna.push(linha);
coluna[0].quantidade++;
console.log(coluna);
alert(coluna[0].quantidade + ' ' + coluna[1].quantidade);
result:
coluna[0].quantidade = 1;
coluna[1].quantidade = 1;
expected
coluna[0].quantidade = 1;
coluna[1].quantidade = 0;
how can I make this?
There are a lot of things to hate about JavaScript, and this is one near the top of my list. There are many ways to resolve your problem, such as Object.assign
and lodash.clonedeep, but the fundamental issue is that unless you take affirmative steps to decouple objects, they are aliased. As you have observed, you have pushed the same object (linha
) onto an array twice, and any modification made to one linha
affects the other one. It would be great if there was some sort of const
feature in the language that prevented you from doing this sort of thing, but unfortunately JavaScript’s const
is worth than useless here.
1 Like
Thanks so much… you helped me to think about this solution,
let linha = { quantidade: 1 };
let coluna = ;
coluna.push({quantidade: linha.quantidade });
coluna.push({quantidade: linha.quantidade });
coluna[0].quantidade++;
console.log(coluna);
alert(coluna[0].quantidade + ’ ’ + coluna[1].quantidade);
Now I can go forward 