Reputation: 257
I got this warning from variable cipher
when I was trying to change a string character at specified index.
const emojis: string[] = [/* values */];
function revealOriginEmojis(cipher: string): string {
for(let i = 0; i < cipher.length; i++){
let index: number = emojis.indexOf(cipher[i]);
cipher[i] = emojis[index];
}
return cipher;
}
So, should I create a new string variable or any better solutions? Thank you so much
Upvotes: 17
Views: 18313
Reputation: 17062
A string
is a primitive value, it's immutable.
you can convert it into array of chars, edit some elements of the array and convert back the array into string.
const cipherChars = [...cipher]; // convert into array
cipherChars[2] = 'X'; // alter array
cipher = cipherChars.join(''); // convert back into string
Upvotes: 25