我想对多个变量进行相同的替换。这是一个有效的示例,但我必须为每个变量编写替换语句。我可以使替换成为一个函数并为每个变量调用该函数,但我想知道是否有一种更有效的方法可以在一行中完成此操作,例如 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>
最佳答案
改用数组,并 .map
到一个新数组,对每个数组执行 replace
操作:
const dogToCat = str => str.replace(/dog/g,'cat');
const strings = [
"I like dogs, dogs are fun",
"The red dog and the brown dog died",
"The dog likes to swim in the ocean"
];
console.log(
strings
.map(dogToCat)
.join('\n')
);
如果您必须使用独立变量并重新分配给它们,那么您可以解构结果,尽管它很难看并且可能不是一个好主意(const
s如果可能的话,最好):
const dogToCat = str => str.replace(/dog/g, 'cat');
let string1 = "I like dogs, dogs are fun";
let string2 = "The red dog and the brown dog died";
let string3 = "The dog likes to swim in the ocean";
([string1, string2, string3] = [string1, string2, string3].map(dogToCat));
console.log(string1 + "\n" + string2 + "\n" + string3);
关于javascript - 如何对 Javascript 中的多个变量进行相同的替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53698360/