JavaScript使用replaceAll替换响应字符串未生效是什么原因?
问题核心
JavaScript 字符串是不可变类型,所有字符串操作方法(包括replaceAll)都不会修改原字符串,只会返回处理后的新字符串。你当前的代码没有接收replaceAll的返回值,替换后的结果直接被丢弃了,因此原变量s没有变化。
修复方案1:修正字符串替换写法
把replaceAll的返回值重新赋值给s即可:
const xhttp = new XMLHttpRequest(); xhttp.onload = function() { let s = xhttp.responseText; // 接收返回值覆盖原变量 s = s.replaceAll("state","item"); s = s.replaceAll("number","count"); const jsonArray = JSON.parse(s); console.log(s); } xhttp.open("GET","http://localhost:8080/plot"); xhttp.send();
修复方案2:更稳妥的JSON属性修改(推荐)
直接修改响应字符串有风险:如果响应的字段值里刚好包含state/number字符串,也会被误替换。更稳妥的方式是先解析JSON,再遍历修改属性名:
const xhttp = new XMLHttpRequest(); xhttp.onload = function() { const jsonArray = JSON.parse(xhttp.responseText); // 遍历数组修改属性名 const modifiedArray = jsonArray.map(item => { return { count: item.number, item: item.state } }) console.log(modifiedArray); } xhttp.open("GET","http://localhost:8080/plot"); xhttp.send();
内容的提问来源于stack exchange,提问作者AmineBinOthman
相关产品推荐
相关产品推荐

