【问题标题】:Why doesn't modify each char of a string?为什么不修改字符串的每个字符?
【发布时间】:2019-09-25 18:05:11
【问题描述】:

我不明白为什么 for 循环不修改字符串的字符。 这是

function testing (str) {
  let other_str = str
  for (let i = 0; i < other_str.length; i++) {
    other_str[i] = 'g'
  }
  return other_str;
}

console.log(testing('hey'));

我知道我可以使用其他方式,但我想了解这一点。

【问题讨论】:

  • 字符串是不可变的。

标签: javascript string for-loop


【解决方案1】:

Strings are immutable ,将字符串转换为数组,进行修改并加入:

function testing(str) {
  let other_str = [...str];
  for (let i = 0; i < other_str.length; i++) {
    other_str[i] = 'g';
  }
  return other_str.join('');
}

console.log(testing('hey'));

【讨论】:

    猜你喜欢
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 2021-08-12
    • 2021-06-14
    相关资源
    最近更新 更多