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

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

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


qq_笑_17
浏览 102回答 1
1回答

猛跑小猪

字符串是不可变的,将字符串转换为数组,进行修改并将其连接回来:function testing(str) {&nbsp; let other_str = [...str];&nbsp; for (let i = 0; i < other_str.length; i++) {&nbsp; &nbsp; other_str[i] = 'g';&nbsp; }&nbsp; return other_str.join('');}console.log(testing('hey'));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript