【问题标题】:Index signature in type 'String' only permits reading“字符串”类型的索引签名只允许读取
【发布时间】:2020-04-12 00:49:57
【问题描述】:

当我尝试更改指定索引处的字符串字符时,我从变量 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;
}

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

【问题讨论】:

  • 一般你可以做类似return origString.split("").map(char =&gt; func(char)).join("");的事情,但我对revealOriginEmojis应该做什么感到很困惑。 emojis[emojis.indexOf(something)] 要么是 something 要么是空字符串,所以你只是过滤原始字符串还是什么?
  • 对不起,emojis const 有值。是的,我想使用 modulo 过滤index 并使用它来获取新索引,然后更改指定索引处的密码字符。

标签: typescript


【解决方案1】:

stringprimitive value,它是不可变的。

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

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

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

cipher = cipherChars.join(); // convert back into string

【讨论】:

  • 如果你得到错误:Type 'string' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. 你可以做const cipherChars = Array.from(cipher); 另见stackoverflow.com/questions/53441292/…
猜你喜欢
  • 1970-01-01
  • 2019-08-16
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
  • 2022-10-16
  • 2010-12-09
  • 1970-01-01
相关资源
最近更新 更多