首页 文章

Javascript - 将trim函数应用于数组中的每个字符串

提问于
浏览
54

想要修剪数组中的每个字符串,例如,给定

x = [' aa ', ' bb '];

产量

['aa', 'bb']

我的第一次试验是

x.map(String.prototype.trim.apply)

它得到了“TypeError:Function.prototype.apply在undefined上调用,这是一个未定义的而不是函数”在chrome中 .

然后我试了一下

x.map(function(s) { return String.prototype.trim.apply(s); });

有用 . 有什么不同?

11 回答

  • 83

    String.prototype.trim.applyFunction.prototype.apply method,不受 trim 的约束 . map将使用字符串,索引和数组作为参数调用它,而thisArg则不调用任何内容( undefined ) - 但是, apply 期望在函数上调用:

    var apply = String.prototype.trim.apply;
    apply.call(undefined, x[0], 0, x) // TypeError
    

    你可以做的是传递 trim 函数作为 call 的上下文:

    [' aa ', ' bb '].map(Function.prototype.call, String.prototype.trim)
    // ['aa', 'bb']
    

    这里发生的是

    var call = Function.prototype.call,
        trim = String.prototype.trim;
    call.call(trim, x[0], 0, x) ≡
          trim.call(x[0], 0, x) ≡
                x[0].trim(0, x); // the arguments don't matter to trim
    
  • 4

    或者这可以通过箭头功能解决:

    x.map(s => s.trim());
    
  • -3

    如果您正在使用JQuery,那么更好的方法是这样做,因为它也适用于IE8(我需要支持IE8)是这样的:

    $.map([' aa ', ' bb ', '   cc '], $.trim);
    
  • 13

    首先,简单地做到:

    x.map(function(s) { return s.trim() });
    

    然后,第一个不起作用的原因是字符串作为参数传递给回调,而不是作为上下文 . 当您没有将参数传递给 apply 时,您会得到与之相同的消息

    var f = String.prototype.trim.apply; f.call();
    

    现在,主要是为了好玩,让's suppose you'对 map 以这种方式使用回调的事实感到不满意,并且你希望能够使用上下文传递函数,而不是参数 .

    然后你可以这样做:

    Object.defineProperty(Array.prototype, "maprec", {
      value: function(cb){
          return this.map(function(v){ return cb.call(v) })
      }
    });
    console.log([' aa ', ' bb '].maprec(String.prototype.trim)); // logs ["aa", "bb"]
    

    我说“主要是为了好玩”,因为修改你不拥有的对象(这里是Array的原型)被广泛认为是一种不好的做法 . 但是你也可以创建一个实用函数,将数组和回调作为参数 .

  • 11

    没有依赖关系的简单变体:

    for (var i = 0; i < array.length; i++) {
         array[i] = array[i].trim()
     }
    

    ES6变体:

    const newArray = oldArray.map(string => string.trim())
    

    ES6功能变体:

    const trimArray = array => array.map(string => string.trim())
    
  • 42

    我只是比较了修剪字符串数组的一些方法,以获得最短和最快的方法 . 谁有兴趣,这里是对jsperf的性能测试:http://jsperf.com/trim-array-of-strings

    var chunks = "  .root  ,  .parent  >  .child  ".split(',')
    var trimmed1 = chunks.map(Function.prototype.call, String.prototype.trim);
    var trimmed2 = chunks.map(function (str) { return str.trim(); });
    var trimmed3 = chunks.map(str => str.trim());
    var trimmed4 = $.map(chunks, $.trim);
    

    注意:jQuery就是在这里比较要键入的字符数;)

  • 3

    从Bergi的影响's perfect answer, i just would like to add, for those methods which won' t采取 this 参数,您可以完成以下相同的工作;

    var x = [' aa ', ' bb '],
        y = x.map(Function.prototype.call.bind(String.prototype.trim))
    
  • 1

    保持简单和愚蠢:

    代码

    [' aa ', ' b b ', '   c c '].map(i=>i.trim());
    

    输出

    ["aa", "b b", "c c"]
    
  • 2
    var x = [" aa ", " bb "];
    console.log(x); // => [" aa ", " bb "]
    
    // remove whitespaces from both sides of each value in the array
    x.forEach(function(value, index){
      x[index] = value.trim();
    });
    
    console.log(x); // => ["aa", "bb"]
    

    所有主流浏览器都支持 forEach() ,但请注意 IE 仅从版本9开始支持它 .

  • -1
    ### Code
        <!-- language: lang-js -->
    
         var x=  [' aa ', ' b b ', '   c c ']
    var x = x.split(",");
                x = x.map(function (el) {
                    return el.trim();
                    console.log(x)
    
        ### Output
        <!-- language: lang-none -->
            ["aa", "b b", "c c"]
    
  • 26

    Another ES6 alternative

    const row_arr = ['a ', ' b' , ' c ', 'd'];
    const trimed_arr = row_arr.map(str => str.trim());
    console.log(trimed_arr); // <== ['a', 'b', 'c', 'd']
    

相关问题