【问题标题】:Replace string in javascript array替换javascript数组中的字符串
【发布时间】:2010-10-31 11:58:14
【问题描述】:

我在 javascript 中有一个数组。此数组包含包含逗号 (",") 的字符串。我希望从此数组中删除所有逗号。这个可以吗?

【问题讨论】:

  • 你不能在字符串被推入数组之前过滤它们吗?否则只是一个简单的 for 循环。
  • 我尝试过,但字符串来自其他地方,动态地。不过没关系,我知道我做错了什么。每个数据库结果后我都留下一个逗号。我确信我所做的数组推送是在每次推送后添加一个逗号。我是JS的初学者。还是谢谢。
  • @MannyCalavera,看看我的回答

标签: javascript arrays string


【解决方案1】:

你也可以用更短的语法内联

array = array.map(x => x.replace(/,/g,""));

【讨论】:

    【解决方案2】:

    您可以使用array.mapforEach。根据我们的场景,array.map 创建或给出一个新数组。 forEach 允许您操作现有数组中的数据。今天我就是这样用的。

    document.addEventListener("DOMContentLoaded", () => {
        // products service
        const products = new Products();
        // get producsts from API.
        products
        .getProducts()
        .then(products => {
            /*
            raw output of data "SHEPPERD'S SALLAD" to "SHEPPERDS SALLAD"
            so I want to get an output like this and just want the object 
            to affect the title proporties. other features should stay 
            the same as it came from the db.
            */ 
            products.forEach(product => product.title = product.title.replace(/'/g,''));
            Storage.saveProducts(products);
        });
    });
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      array = ["erf,","erfeer,rf","erfer"];
      array = array.map(function(x){ return x.replace(/,/g,"") });
      

      现在数组变成了:

      ["erf", "erfeerrf", "erfer"]

      【讨论】:

      • 您不需要(阅读:不应该)自己测试正则表达式,无论如何这都会发生在幕后。
      【解决方案4】:

      现在最好的方法是这样使用map()函数:

      var resultArr = arr.map(function(x){return x.replace(/,/g, '');});
      

      这是 ECMA-262 标准。 如果你需要它的早期版本,你可以在你的项目中添加这段代码:

      if (!Array.prototype.map)
      {
          Array.prototype.map = function(fun /*, thisp*/)
          {
              var len = this.length;
              if (typeof fun != "function")
                throw new TypeError();
      
              var res = new Array(len);
              var thisp = arguments[1];
              for (var i = 0; i < len; i++)
              {
                  if (i in this)
                      res[i] = fun.call(thisp, this[i], i, this);
              }
      
              return res;
          };
      }
      

      【讨论】:

        【解决方案5】:

        是的。

        for(var i=0; i < arr.length; i++) {
         arr[i] = arr[i].replace(/,/g, '');
        }
        

        【讨论】:

        • +1 表示比我更接近,但您需要对结果做一些事情,replace 不会改变字符串。
        • 对不起kekoav,不应该是:arr[i] = arr[i].replace(/,/g, ''); ??
        【解决方案6】:

        当然——只需遍历数组并在每次迭代时执行标准删除。

        或者,如果您的数组性质允许,您可以先将数组转换为字符串,去掉逗号,然后再转换回数组。

        【讨论】:

          猜你喜欢
          • 2014-12-31
          • 2021-12-26
          • 1970-01-01
          • 1970-01-01
          • 2016-11-17
          • 2012-04-26
          • 2010-09-28
          • 1970-01-01
          • 2013-08-30
          相关资源
          最近更新 更多