为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

qq_笑_17 2021-10-29 10:52:00
我不明白为什么 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 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

字符串是不可变的,将字符串转换为数组,进行修改并将其连接回来:


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


查看完整回答
反对 回复 2021-10-29
  • 1 回答
  • 0 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信