I'm doing some string manipulation by splitting the string using .split('')
, then iterating through it with a for
loop, then using .join('')
to reassemble it. I coded the split, loop, and join, and everything worked fine. But I decided to do another for loop operation on the string before the loop I already had, but after the split, and I ran into this. Before I even get to the loop, those values are showing up in the array! What is going on?
Here's a sample program showing the problem stripped to bare bones.
var someFunction = function () {
var foo = '';
foo = foo + 'Hello, world!';
console.log(foo);
console.log(foo.split(''));
foo = foo.split('');
console.log(foo); // <-- This is the call causing me issues
for(var i = 0; i < foo.length; i++) {
foo[i] += 'bar';
}
foo = foo.join('');
console.log(foo);
};
someFunction();
This outputs:
Hello, world!
Array(13) [ "H", "e", "l", "l", "o", ",", " ", "w", "o", "r", … ]
Array(13) [ "H", "e", "l", "l", "o", ",", " ", "w", "o", "r", … ] //<-- This is the marked console.log call
[
0: "Hbar" //<-- This is the array expanded so you can see the values inside
1: "ebar"
2: "lbar"
3: "lbar"
4: "obar"
5: ",bar"
6: " bar"
7: "wbar"
8: "obar"
9: "rbar"
10: "lbar"
11: "dbar"
12: "!bar"
]
Hbarebarlbarlbarobar,bar barwbarobarrbarlbardbar!bar
It's really stumping me!