我不明白为什么 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 回答
![?](http://img1.sycdn.imooc.com/533e50ed0001cc5b02000200-100-100.jpg)
猛跑小猪
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'));
添加回答
举报
0/150
提交
取消