为什么不修改字符串的每个字符?

时间:2019-09-25 18:05:11

标签: javascript string for-loop

我不明白为什么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'));

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

1 个答案:

答案 0 :(得分:2)

MIF 7.6 Message tracking changes,将字符串转换为数组,进行修改并重新加入:

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'));