I have the following code:
const heroes = [
{ name: 'Wolverine', family: 'Marvel', isEvil: false },
{ name: 'Deadpool', family: 'Marvel', isEvil: false },
{ name: 'Magneto', family: 'Marvel', isEvil: true },
{ name: 'Charles Xavier', family: 'Marvel', isEvil: false },
{ name: 'Batman', family: 'DC Comics', isEvil: false },
{ name: 'Harley Quinn', family: 'DC Comics', isEvil: true },
{ name: 'Legolas', family: 'Tolkien', isEvil: false },
{ name: 'Gandalf', family: 'Tolkien', isEvil: false },
{ name: 'Saruman', family: 'Tolkien', isEvil: true }
]
var newHeroes = heroes.slice(0);
newHeroes[0] = { name: 'Test', family: '2', isEvil: false };
newHeroes[1].name = 'Test 2';
console.log(newHeroes);
console.log(heroes);
As soon as I'm slicing the first array, I expected the second to be a non-memory copy of the heroes const. So, whenever I change the newHeroes array, I thought that the first one wouldn't change.
When I change the entire content (like newHeroes[0] = Object), it works perfectly. This changes the second array only.
But when I try to change the property directly (newHeroes[1].name = 'Test 2'), it changes in both arrays.
Does anybody could explain me why?
Thank you! :-)