在此上下文中/.map 方法中,.replace 方法的适当用途是什么?

What is the appropriate use for the .replace method within this context/ within a .map method?

我正在尝试遍历一个字符串数组,并针对该数组中的每个元素(字符串),将“_”下划线字符后的字符更改为“*”字符。字符串是不可变的,因此将其全部推送到一个新数组。

当直接针对下划线进行替换时,该链按预期执行:

const t1 = ['underscore_case', 'first_name', 'some_variable', 'calculate_age', 'delayed_departure']
const t2 = t1.map(e => e.replace(e[e.indexOf('_')], '*'))
// Output: ['underscore*case', 'first*name', 'some*variable', 'calculate*age', 'delayed*departure']

但是在追求实际预期功能的那一刻,修改下划线后面的字符 - 输出变得几乎疯狂,“*”在每个字符串中以随机间隔出现。在以下两种尝试中:

const t1 = ['underscore_case', 'first_name', 'some_variable', 'calculate_age', 'delayed_departure']
const t2 = t1.map(e => e.replace(e[e.indexOf('_')+1], '*'))
// Output: ['unders*ore_case', 'first_*ame', 'some_*ariable', 'c*lculate_age', '*elayed_departure']

以及,在有些绝望之后,像这样手动输入索引:

const t1 = ['underscore_case', 'first_name', 'some_variable', 'calculate_age', 'delayed_departure']
const t2 = t1.map(e => e.replace(e[5], '*'))
// Output: ['under*core_case', 'first*name', 'some_*ariable', 'ca*culate_age', 'd*layed_departure']

实验表明,出于某种原因,意外行为,尤其是在最后两个元素中,仅当手动指定的索引值出于某种原因超过或等于 5 时才会出现?

为什么会这样?

在尝试了几个小时的各种循环方法并在链接之外分解了每个操作之后,我在使用 replace 方法时总是返回相同的结果,无论这种情况发生在哪里 - 并且不得不使用涉及切片的解决方法方法和模板文字。

下划线后面的字符也可能出现在字符串的较早位置,在这种情况下,replace 调用将找到 that 出现并替换它.

例如,对于“calculate_age”,e[indexOf("_")+1] 将求值为“a”(属于“年龄”),但 replace 会在字符串的开头,并将 that 替换为星号。

相反,为此使用正则表达式:

const t1 = ['underscore_case', 'first_name', 'some_variable', 'calculate_age', 'delayed_departure'];
const t2 = t1.map(e => e.replace(/_./g, '_*'));

console.log(t2);

正则表达式中的点是通配符。所以无论它是什么(换行符除外),它都会被替换(连同下划线)为“_*”。

关于你写的:

Strings are immutable so, pushing this all to a new array.

是的,字符串是不可变的,但数组是可变的,因此您可能已经决定用替换项替换该数组中的所有字符串。然后你改变数组,而不是字符串。

话虽如此,创建一个新数组很好(也是很好的函数式编程)。