【问题标题】:Replace all same values in array with other same values用其他相同的值替换数组中的所有相同值
【发布时间】:2026-01-11 03:20:03
【问题描述】:

我想在以下代码中将所有“John”替换为“Margaret”:

array = ["John", "John", "Herald", "John"]

我尝试过: array[array.indexOf('John')] = 'Margaret',但这会中断。 我将 React.js 与 TypeScript 一起使用。

【问题讨论】:

  • 这能回答你的问题吗? How to replace item in array?
  • @gorak 虽然逻辑上相似,但并不完全重复。这个问题想要替换数组中满足条件的所有元素,而不仅仅是第一个,并且接受的答案只是改变数组,我们通常在 React 中避免这种情况。
  • @DrewReese 看看这个问题的答案*.com/a/5915891/10004893

标签: javascript reactjs


【解决方案1】:

您将(应该)需要映射到一个新数组,以避免数组突变。

["John", "John", "Herald", "John"].map(el => el === 'John' ? 'Margaret' : el);

const array = ["John", "John", "Herald", "John"].map(el => el === 'John' ? 'Margaret' : el);

console.log(array);

【讨论】:

    【解决方案2】:

    const array = ["John", "John", "Herald", "John"]
    array.forEach((element, index) => {
       if(element === 'John') {
          array[index] = 'Margaret';
       }
     });
    
    console.log(array); // ["Margaret", "Margaret", "Herald", "Margaret"]

    【讨论】:

      【解决方案3】:

      我个人会选择 Drew Reese,因为它是单行的,而且答案很清晰,但如果需要详细说明,请参阅下面的答案。

      map() 方法创建一个新数组,其中填充了对调用数组中的每个元素调用提供的函数的结果。

      const array1 = ["John", "John", "Herald", "John"];
      
      // pass a function to map
      const map1 = array1.map(el => el === 'John' ? 'Margaret' : el);
      
      console.log(map1);
      // expected output: Array ["Margaret", "Margaret", "Herald", "Margaret"]
      
      

      【讨论】:

        【解决方案4】:
        function replaceAll(arr, valueToReplace, replaceWith) {
          return arr.map(e => valueToReplace === e ? replaceWith : e)
        }
        

        【讨论】:

        • 虽然此代码可能会为问题提供解决方案,但最好添加有关其工作原理/方式的上下文。这可以帮助未来的用户学习并最终将这些知识应用到他们自己的代码中。解释代码时,您也可能会得到用户的积极反馈/赞成。
        【解决方案5】:

        我认为您应该编写一个原型以便更好地重用和输入替换。

        Array.prototype.replaceAll = function(find, replace){
            return this.map(function(item){
                return item === find ? replace : item;
            });
        }
        

        参见:https://i.imgur.com/8zK57co.png

        【讨论】:

          【解决方案6】:

          const names = ["John", "John", "Herald", "John"]
            .join(" ")
            .replace(/John/g, "Margaret")
            .split(" ");
          
          console.log(names);

          【讨论】:

            最近更新 更多