【问题标题】:How to replace item in array?如何替换数组中的项目?
【发布时间】:2011-08-20 10:08:52
【问题描述】:

这个数组的每一项都是一些数字:

var items = Array(523,3452,334,31, ...5346);

如何用新的替换一些项目?

例如,我们想用1010替换3452,我们该怎么做呢?

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    当你的数组有很多个旧项目来替换新项目时,你可以这样使用:

    function replaceArray(array, oldItem, newItem) {
        for (let i = 0; i < array.length; i++) {
            const index = array.indexOf(oldItem);
            if (~index) {
                array[index] = newItem;
            }
        }
        return array
    }
    
    console.log(replaceArray([1, 2, 3, 2, 2, 8, 1, 9], 2, 5));
    console.log(replaceArray([1, 2, 3, 2, 2, 8, 1, 9], 2, "Hi"));

    【讨论】:

      【解决方案2】:

      @gilly3 的回答很好。

      替换对象数组中的对象,保持元素顺序不变

      当我从服务器获取数据时,我更喜欢以下方式将新更新的记录更新到我的记录数组中。它使订单保持原样,并且非常直接一个班轮。

      users = users.map(u =&gt; u.id !== editedUser.id ? u : editedUser);

      var users = [
      {id: 1, firstname: 'John', lastname: 'Ken'},
      {id: 2, firstname: 'Robin', lastname: 'Hood'},
      {id: 3, firstname: 'William', lastname: 'Cook'}
      ];
      
      var editedUser = {id: 2, firstname: 'Michael', lastname: 'Angelo'};
      
      users = users.map(u => u.id !== editedUser.id ? u : editedUser);
      
      console.log('users -> ', users);

      【讨论】:

        【解决方案3】:

        在 javascript 中替换数组元素的函数式方法:

        const replace = (array, index, ...items) =&gt; [...array.slice(0, index), ...items, ...array.slice(index + 1)];

        【讨论】:

          【解决方案4】:

          使用indexOf 查找元素。

          var i = items.indexOf(3452);
          items[i] = 1010;
          

          【讨论】:

          • 如果它不是预期的元素怎么办。如果找到它将返回找到的元素的索引,但如果没有,它将返回 -1。它将将该值设置为-1。请参考jsbin.com/wugatuwora/edit?js,console
          【解决方案5】:
           items[items.indexOf(3452)] = 1010
          

          非常适合简单的交换。试试下面的sn-p

          const items = Array(523, 3452, 334, 31, 5346);
          console.log(items)
          
          items[items.indexOf(3452)] = 1010
          console.log(items)

          【讨论】:

            【解决方案6】:

            如果您想要一个简单的糖 sintax oneliner,您可以:

            (elements = elements.filter(element => element.id !== updatedElement.id)).push(updatedElement);
            

            喜欢:

            let elements = [ { id: 1, name: 'element one' }, { id: 2, name: 'element two'} ];
            const updatedElement = { id: 1, name: 'updated element one' };
            

            如果你没有 id,你可以像这样对元素进行字符串化:

            (elements = elements.filter(element => JSON.stringify(element) !== JSON.stringify(updatedElement))).push(updatedElement);
            

            【讨论】:

              【解决方案7】:

              这是一个单线。它假定该项目将在数组中。

              var items = [523, 3452, 334, 31, 5346]
              var replace = (arr, oldVal, newVal) => (arr[arr.indexOf(oldVal)] = newVal, arr)
              console.log(replace(items, 3452, 1010))

              【讨论】:

                【解决方案8】:

                ES6方式:

                const items = Array(523, 3452, 334, 31, ...5346);
                

                我们想用1010替换3452,解决方案:

                const newItems = items.map(item => item === 3452 ? 1010 : item);
                

                当然,这个问题是多年前的问题,而现在我更喜欢使用 immutable 解决方案,当然,这对ReactJS 来说太棒了。

                为了经常使用,我提供以下功能:

                const itemReplacer = (array, oldItem, newItem) =>
                  array.map(item => item === oldItem ? newItem : item);
                

                【讨论】:

                  【解决方案9】:

                  第一种方法

                  在一行中替换或更新数组项的最佳方式

                  array.splice(array.indexOf(valueToReplace), 1, newValue)
                  

                  例如:

                  let items = ['JS', 'PHP', 'RUBY'];
                  
                  let replacedItem = items.splice(items.indexOf('RUBY'), 1, 'PYTHON')
                  
                  console.log(replacedItem) //['RUBY']
                  console.log(items) //['JS', 'PHP', 'PYTHON']
                  

                  第二种方法

                  进行相同操作的另一种简单方法是:

                  items[items.indexOf(oldValue)] = newValue
                  

                  【讨论】:

                  • 请注意,如果在原始数组中找不到要替换的值,这两种方法都会出现异常,因为如果找不到元素,则 Array.indexOf() 将返回 -1。
                  【解决方案10】:

                  如果有人对如何从数组中的索引替换对象感兴趣,这里有一个解决方案。

                  通过 id 查找对象的索引:

                  const index = items.map(item => item.id).indexOf(objectId)
                  

                  使用 Object.assign() 方法替换对象:

                  Object.assign(items[index], newValue)
                  

                  【讨论】:

                  【解决方案11】:

                  最简单的方法就是这样。

                  var items = Array(523,3452,334,31, 5346);
                  var replaceWhat = 3452, replaceWith = 1010;
                  if ( ( i = items.indexOf(replaceWhat) ) >=0 ) items.splice(i, 1, replaceWith);
                  
                  console.log(items);
                  >>> (5) [523, 1010, 334, 31, 5346]
                  

                  【讨论】:

                  • 不适用于在索引 0 找到的项目 replaceWhat = 523, replaceWith = 999999 不会产生正确的结果
                  【解决方案12】:
                  presentPrompt(id,productqty) {
                      let alert = this.forgotCtrl.create({
                        title: 'Test',
                        inputs: [
                          {
                            name: 'pickqty',
                            placeholder: 'pick quantity'
                          },
                          {
                            name: 'state',
                            value: 'verified',
                            disabled:true,
                            placeholder: 'state',
                  
                          }
                        ],
                        buttons: [
                          {
                            text: 'Ok',
                            role: 'cancel',
                            handler: data => {
                  
                              console.log('dataaaaname',data.pickqty);
                              console.log('dataaaapwd',data.state);
                  
                  
                            for (var i = 0; i < this.cottonLists.length; i++){
                  
                              if (this.cottonLists[i].id == id){
                                  this.cottonLists[i].real_stock = data.pickqty;
                  
                              }
                            }
                  
                            for (var i = 0; i < this.cottonLists.length; i++){
                  
                              if (this.cottonLists[i].id == id){
                                this.cottonLists[i].state = 'verified';   
                  
                            }
                          }
                              //Log object to console again.
                              console.log("After update: ", this.cottonLists)
                              console.log('Ok clicked');
                            }
                          },
                  
                        ]
                      });
                      alert.present();
                    }
                  
                  As per your requirement you can change fields and array names.
                  thats all. Enjoy your coding.
                  

                  【讨论】:

                    【解决方案13】:
                    var index = Array.indexOf(Array value);
                            if (index > -1) {
                              Array.splice(index, 1);
                            }
                    

                    从这里你可以从数组中删除一个特定的值并基于相同的索引 你可以在数组中插入值。

                     Array.splice(index, 0, Array value);
                    

                    【讨论】:

                      【解决方案14】:

                      使用 ES6 扩展运算符和.slice 方法替换列表中元素的不可变方式。

                      const arr = ['fir', 'next', 'third'], item = 'next'
                      
                      const nextArr = [
                        ...arr.slice(0, arr.indexOf(item)), 
                        'second',
                        ...arr.slice(arr.indexOf(item) + 1)
                      ]
                      

                      验证是否有效

                      console.log(arr)     // [ 'fir', 'next', 'third' ]
                      console.log(nextArr) // ['fir', 'second', 'third']
                      

                      【讨论】:

                      • 非常低估的解决方案。
                      【解决方案15】:

                      我建议的解决方案是:

                      items.splice(1, 1, 1010);
                      

                      拼接操作将从数组中的位置 1 开始删除 1 个项目(即3452),并将其替换为新项目 1010

                      【讨论】:

                      【解决方案16】:

                      替换可以在一行中完成:

                      var items = Array(523, 3452, 334, 31, 5346);
                      
                      items[items.map((e, i) => [i, e]).filter(e => e[1] == 3452)[0][0]] = 1010
                      
                      console.log(items);

                      或者创建一个函数来重用:

                      Array.prototype.replace = function(t, v) {
                          if (this.indexOf(t)!= -1)
                              this[this.map((e, i) => [i, e]).filter(e => e[1] == t)[0][0]] = v;
                        };
                      
                      //Check
                      var items = Array(523, 3452, 334, 31, 5346);
                      items.replace(3452, 1010);
                      console.log(items);

                      【讨论】:

                        【解决方案17】:

                        如果使用复杂对象(甚至是简单对象)并且可以使用 es6,Array.prototype.findIndex 是一个很好的对象。对于OP的数组,他们可以做到,

                        const index = items.findIndex(x => x === 3452)
                        items[index] = 1010
                        

                        对于更复杂的对象,这真的很出色。例如,

                        const index = 
                            items.findIndex(
                               x => x.jerseyNumber === 9 && x.school === 'Ohio State'
                            )
                        
                        items[index].lastName = 'Utah'
                        items[index].firstName = 'Johnny'
                        

                        【讨论】:

                        • 请注意,如果在原始数组中找不到要替换的值,这两种方法都会出现异常,因为如果找不到元素,则 Array.indexOf() 将返回 -1。在第一种情况下,它将向您的数组添加一个索引为 -1 的元素,这将使您的数组在许多方面表现出意外。在第二种情况下,它会因为尝试设置 undefined 的属性而崩溃。
                        【解决方案18】:

                        我使用 for 循环解决了这个问题,遍历原始数组并将匹配区域的位置添加到另一个数组,然后循环遍历该数组并在原始数组中更改它然后返回它,我使用了箭头函数但是常规功能也可以。

                        var replace = (arr, replaceThis, WithThis) => {
                            if (!Array.isArray(arr)) throw new RangeError("Error");
                            var itemSpots = [];
                            for (var i = 0; i < arr.length; i++) {
                                if (arr[i] == replaceThis) itemSpots.push(i);
                            }
                        
                            for (var i = 0; i < itemSpots.length; i++) {
                                arr[itemSpots[i]] = WithThis;
                            }
                        
                            return arr;
                        };
                        

                        【讨论】:

                          【解决方案19】:

                          这是一个可重用函数的基本答案:

                          function arrayFindReplace(array, findValue, replaceValue){
                              while(array.indexOf(findValue) !== -1){
                                  let index = array.indexOf(findValue);
                                  array[index] = replaceValue;
                              }
                          }
                          

                          【讨论】:

                          • 让索引; while((index = indexOf(findValue)) !== -1) 避免双重 indexOf(findValue)
                          【解决方案20】:

                          您可以使用索引编辑任意数量的列表

                          例如:

                          items[0] = 5;
                          items[5] = 100;
                          

                          【讨论】:

                            【解决方案21】:

                            首先,像这样重写你的数组:

                            var items = [523,3452,334,31,...5346];
                            

                            接下来,通过索引号访问数组中的元素。确定索引号的公式为:n-1

                            要替换数组中的第一项(n=1),请编写:

                            items[0] = Enter Your New Number;
                            

                            在您的示例中,数字3452 位于第二位(n=2)。所以确定索引号的公式是2-1 = 1。所以编写以下代码将3452替换为1010

                            items[1] = 1010;
                            

                            【讨论】:

                              【解决方案22】:
                              var index = items.indexOf(3452);
                              
                              if (index !== -1) {
                                  items[index] = 1010;
                              }
                              

                              另外,建议您不要使用构造函数方法来初始化您的数组。而是使用文字语法:

                              var items = [523, 3452, 334, 31, 5346];
                              

                              如果您使用简洁的 JavaScript 并希望缩短 -1 比较,也可以使用 ~ 运算符:

                              var index = items.indexOf(3452);
                              
                              if (~index) {
                                  items[index] = 1010;
                              }
                              

                              有时我什至喜欢写一个contains 函数来抽象这个检查,让人们更容易理解发生了什么。令人敬畏的是这适用于数组和字符串:

                              var contains = function (haystack, needle) {
                                  return !!~haystack.indexOf(needle);
                              };
                              
                              // can be used like so now:
                              if (contains(items, 3452)) {
                                  // do something else...
                              }
                              

                              从 ES6/ES2015 开始用于字符串,并建议用于 ES2016 用于数组,您可以更轻松地确定源是否包含另一个值:

                              if (haystack.includes(needle)) {
                                  // do your thing
                              }
                              

                              【讨论】:

                              • @ValRob 你可以使用findIndex。看到这个答案:stackoverflow.com/a/53952276/2430274
                              • 请问比较中的 index !== -1 代表什么。谢谢
                              • @coderboy 有点晚,但如果在数组中未找到要搜索的值,indexOf 函数将返回 -1。
                              【解决方案23】:
                              var items = Array(523,3452,334,31,5346);
                              

                              如果你知道值然后使用,

                              items[items.indexOf(334)] = 1010;
                              

                              如果您想知道该值是否存在,请使用,

                              var point = items.indexOf(334);
                              
                              if (point !== -1) {
                                  items[point] = 1010;
                              }
                              

                              如果你知道地点(位置)那么直接使用,

                              items[--position] = 1010;
                              

                              如果你想替换几个元素,而你只知道起始位置意味着,

                              items.splice(2, 1, 1010, 1220);
                              

                              更多关于.splice

                              【讨论】:

                                【解决方案24】:

                                最简单的方法是使用一些库,例如underscorejs 和 map 方法。

                                var items = Array(523,3452,334,31,...5346);
                                
                                _.map(items, function(num) {
                                  return (num == 3452) ? 1010 : num; 
                                });
                                => [523, 1010, 334, 31, ...5346]
                                

                                【讨论】:

                                  【解决方案25】:

                                  Array.indexOf() 方法将替换第一个实例。要获取每个实例,请使用 Array.map():

                                  a = a.map(function(item) { return item == 3452 ? 1010 : item; });
                                  

                                  当然,这会创建一个新数组。如果你想就地做,使用Array.forEach()

                                  a.forEach(function(item, i) { if (item == 3452) a[i] = 1010; });
                                  

                                  【讨论】:

                                  • 对于其他阅读本文的人。 map() 和 forEach() 都是对 Javascript 规范的较新添加,并且在某些较旧的浏览器中不存在。如果你想使用它们,你可能需要添加旧浏览器的兼容性代码:developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
                                  • Array.indexOf()map()forEach() 同时引入。如果您支持 IE8 或更早版本,并且您没有使用 shim 来添加支持,最好使用 mellamokb's answer
                                  • array.map 也在其第二个参数中返回索引 a = a.map(function(item,key) { if (item == 3452) a[key] = 1010; });跨度>
                                  • @Rickysharma 您也可以对地图执行此操作,但是,它只会重写旧数组中的值,然后创建该值的副本并返回它。因此,三元运算符的工作效率更高。
                                  【解决方案26】:

                                  使用for 循环轻松完成。

                                  for (var i = 0; i < items.length; i++)
                                      if (items[i] == 3452)
                                          items[i] = 1010;
                                  

                                  【讨论】:

                                  • 注意:如果您使用嵌套的 for 循环,这将是性能最佳的技术,因为您可以在找到并替换所有需要的元素后立即中断循环
                                  猜你喜欢
                                  • 2011-01-21
                                  • 2018-02-14
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 2017-07-31
                                  • 2016-06-10
                                  相关资源
                                  最近更新 更多