I can’t figure out what’s going on. I add an object to the array, it is added, but the old data copies the values from the new object. This is the first time I’ve encountered this.
Here is the code
var news = []
var next
if(cart === null){
next = 0
}else {
next = cart.length
}
switch(type){
case 'horizontal':
config['0']['type'] = type
config['0']['id'] = next
config['0'].idImg = selectSvg
if(cart === null || cart === undefined || cart.length < 1){
news.push(config)
setCountCart(news.length)
localStorage.setItem('cart-tagstyle', JSON.stringify(news))
setCart(news)
}else {
var news = cart.slice()
console.log(news);
news.push(config)
console.log(news);
setCountCart(news.length)
localStorage.setItem('cart-tagstyle', JSON.stringify(news))
setCart(news)
}
break;
I tried it without push, according to the following index, the same thing. I searched the Internet, it didn’t help. I’ve been suffering for the second day
2
Answers
Due to this old data copies value from new objects. Check the below code where the index is changed
if I understand the problem correctly,
the problem is that because arrays are reference types. Which means when you assign an array to a variable, you’re assigning a memory address and not the actual array itself,
so you should use deep clone for solving that or use
than changing
newArray
will not effectsoldArray
checkout this link for more info
https://dev.to/samanthaming/how-to-deep-clone-an-array-in-javascript-3cig