I have such part of code
console.log(b);
let c = b.substr(0);
console.log(b[b.length - 1] + ' ' + c[Math.floor(c.length / 2)]);
c[Math.floor(c.length / 2)] = b[b.length - 1];
console.log(b[b.length - 1] + ' ' + c[Math.floor(c.length / 2)]);
//some code changing c
console.log(c);
And it seems like c and b are the same part of memory, because console.log(c);
and console.log(b);
give the same result, and two other console.logs give same results, when the second one should obviously give two same values (it gives different ones). How to copy a value of a variable correctly and without making something weird like JSON.parse(JSON.stringify(b))
? Is there a time- and memory- effective way to do that in JS?
The substr function returns a new String (new object), hence c and b are not the same objects.
Also, changing a String by assigning a different character to some index doesn't work as it doesn't change the original object.
If what you seek to do is replacing a character at a specific index, here's a useful post: How do I replace a character at a particular index in JavaScript?