在 for 循环中使用 String.replace

Using String.replace in a for loop

for (var z = 0; z < spells[0].vars.length; z++) {
    if (spells[0].sanitizedTooltip.indexOf(spells[0].vars[z].key) > -1) {
        var key = spells[0].vars[z].key;
        sanitizedOut = spells[0].sanitizedTooltip.replace("{{ " + key + " }}", spells[0].vars[z].coeff);
    }
}

这段代码是为了替换一个字符串中的多个"keys"。但是,只有最后一次被替换。

Throws a dagger dealing {{ e2 }} (+{{ a1 }}) magic damage. The dagger bounces to the 4 closest enemies dealing 10% less damage with each bounce. Enemies hit are marked for 4 seconds. Katarina's basic attacks or spells will consume the mark dealing {{ e3 }} (+{{ a2 }}) additional magic damage.

这是sanitizedTooltipspells[0].vars 是:

[ { key: 'a1', link: 'spelldamage', coeff: [ 0.45 ] }, { key: 'a2', link: 'spelldamage', coeff: [ 0.15 ] } ]

但是,这个for循环的结果只有returns:

Throws a dagger dealing {{ e2 }} (+{{ a1 }}) magic damage. The dagger bounces to the 4 closest enemies dealing 10% less damage with each bounce. Enemies hit are marked for 4 seconds. Katarina's basic attacks or spells will consume the mark dealing {{ e3 }} (+0.15) additional magic damage.

...其中 {{ a1 }} 预计为 +0.45。提前致谢!

循环的每次迭代都对原始 spells[0].sanitizedTooltip 进行操作。每次通过时,sanitizedOut 都会重新分配最新迭代的结果,因此当循环退出时,您只会看到最后的结果。

为了帮助您在一次调用中替换所有出现的事件,您可以构建一个递归函数,如下所示:

function replaceAll(value, oldChar, newChar) {
   if (value.indexOf(oldChar) > -1) {
      value = value.replace(oldChar, newChar);
      return replaceAll(value, oldChar, newChar);
   } else {
      return value;
   }
}

var s = "A B A B A B A B";
s = replaceAll(s, "A" , "X");
alert(s);

结果将是:X B X B X B X B