我想对多个变量做同样的替换 . 在这里's an example that works, but I have to write the replace statement for each variable. I could make the replace a function and call the function for each variable, but I was wondering if there'是一种更有效的方式在一行中完成它,比如 string1,string2,string3(replace...
<script>
string1="I like dogs, dogs are fun";
string2="The red dog and the brown dog died";
string3="The dog likes to swim in the ocean";
string1=string1.replace(/dog/g,'cat');
string2=string2.replace(/dog/g,'cat');
string3=string3.replace(/dog/g,'cat');
alert(string1+"\n"+string2+"\n"+string3);
</script>
1 回答
改为使用数组,并使用
.map
到一个新数组,在每个数组上执行replace
操作:如果你必须使用独立变量并重新分配给它们,那么你可以对结果进行解构,虽然它是一个好主意(如果可能,
const
s更可取):