首页 文章

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

提问于
浏览
0

我想对多个变量做同样的替换 . 在这里'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 回答

  • 1

    改为使用数组,并使用 .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);
    

相关问题