Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Javascript中对多个变量执行相同的替换_Javascript_String_Replace - Fatal编程技术网

如何在Javascript中对多个变量执行相同的替换

如何在Javascript中对多个变量执行相同的替换,javascript,string,replace,Javascript,String,Replace,我想对多个变量做同样的替换。下面是一个有效的示例,但我必须为每个变量编写replace语句。我可以将replace设置为一个函数并为每个变量调用该函数,但我想知道是否有更有效的方法在一行中执行,比如string1、string2、string3(replace… <script> string1="I like dogs, dogs are fun"; string2="The red dog and the brown dog died"; string3="The dog lik

我想对多个变量做同样的替换。下面是一个有效的示例,但我必须为每个变量编写replace语句。我可以将replace设置为一个函数并为每个变量调用该函数,但我想知道是否有更有效的方法在一行中执行,比如
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>

string1=“我喜欢狗,狗很有趣”;
string2=“红狗和棕色狗死了”;
string3=“狗喜欢在海里游泳”;
string1=string1.替换(/dog/g,'cat');
string2=string2.替换(/dog/g,'cat');
string3=string3.替换(/dog/g,'cat');
警报(string1+“\n”+string2+“\n”+string3);

改为使用数组,并将
映射到新数组,对每个数组执行
替换
操作:

constdogtocat=str=>str.replace(/dog/g,'cat');
常量字符串=[
“我喜欢狗,狗很有趣”,
“红狗和棕色狗死了”,
“狗喜欢在海里游泳”
];
console.log(
串
.map(dogToCat)
.join(“\n”)

);
谢谢,我确实需要保持变量的完整性,但这并不能像我希望的那样真正简化它。如果必须重新分配每个变量,则无法将变量名写两次(请参见类似问题)
.map快捷方式加上解构几乎是唯一的“缩短”选项(如果要保留字符,请随意删除命名回调)