'String' 类型的索引签名只允许读取

Fan*_*sbi 7 typescript

cipher当我尝试更改指定索引处的字符串字符时,我从变量中收到此警告。

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;
}
Run Code Online (Sandbox Code Playgroud)

那么,我应该创建一个新的字符串变量还是任何更好的解决方案?非常感谢

Yuk*_*élé 10

Astring是一个原始值,它是不可变的。

您可以将其转换为字符数组,编辑数组的某些元素并将数组转换回字符串。

const cipherChars = [...cipher]; // convert into array

cipherChars[2] = 'X'; // alter array

cipher = cipherChars.join(); // convert back into string
Run Code Online (Sandbox Code Playgroud)

  • 如果出现错误:“类型‘string’不是数组类型或字符串类型。使用编译器选项“--downlevelIteration”允许迭代器迭代。您可以执行“const cipherChars = Array.from(cipher);”另请参阅/sf/ask/3740890471/默认不开启 (2认同)