【问题标题】:Using replace string method inside forEach在 forEach 中使用替换字符串方法
【发布时间】:2020-12-06 05:51:38
【问题描述】:

我有一个充满字符串的数组,我想循环并用 '' 替换任何出现的 '123'。

期望的结果是:['hello', 'cats', 'world', 'dogs']

let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];

arr.forEach(x => {
  x.replace('123', '');
});

【问题讨论】:

  • const replacedStrings = arr.map(word => word.replace(/123/g, ''))
  • forEach() 返回undefined,你应该使用Array.prototype.map() insted,顺便说一句,如果你想替换,最好使用.replace(/123/g, '')所有次出现不需要的子串

标签: javascript


【解决方案1】:

如果可以,请改用.map - 在回调中返回.replace 调用:

let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];

const result = arr.map(x => x.replace('123', ''));
console.log(result);

如果您必须就地改变数组,那么也获取索引,并将 .replace 回调分配给数组中的该索引:

let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];

arr.forEach((x, i) => arr[i] = x.replace('123', ''));
console.log(arr);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-08
    • 2012-09-25
    • 2019-02-11
    • 1970-01-01
    • 2016-02-26
    相关资源
    最近更新 更多