Javascript - Apply trim function to each string in an array

后端 未结 11 1330
-上瘾入骨i
-上瘾入骨i 2020-12-07 14:22

Want to trim each string in an array, e.g., given

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

output

[\'aa\', \'bb\']

My fi

相关标签:
11条回答
  • 2020-12-07 14:37

    First, do it simply :

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

    Then, the reason why the first one doesn't work is that the string is passed as argument to the callback, not as context. As you pass no argument to apply, you get the same message you would have got with

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

    Now, mostly for fun, let's suppose you're not happy with the fact that map use the callback this way and you'd want to be able to pass a function using the context, not the argument.

    Then you could do this :

    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"]
    

    I said "mostly for fun" because modifying objects you don't own (Array's prototype here) is widely seen as a bad practice. But you could also make a utilitarian function taking both the array and the callback as arguments.

    0 讨论(0)
  • 2020-12-07 14:37

    Keep it simple and stupid:

    Code

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

    Output

    ["aa", "b b", "c c"]
    
    0 讨论(0)
  • 2020-12-07 14:43
        ### 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"]     
    
    0 讨论(0)
  • 2020-12-07 14:47
    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"]
    

    All major browsers support forEach(), but note that IE supports it only beginning from version 9.

    0 讨论(0)
  • 2020-12-07 14:49

    I just compared some ways to trim an array of strings to get the shortest and fastest method. Who is interested in, here is a performance test on 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);
    

    Note: jQuery is just here to compare the number of characters to type ;)

    0 讨论(0)
  • 2020-12-07 14:54

    Influencing from Bergi's perfect answer, i just would like to add, for those methods which won't take a this argument, you may achieve the same job as follows;

    var x = [' aa ', ' bb '],
        y = x.map(Function.prototype.call.bind(String.prototype.trim))
    
    0 讨论(0)
提交回复
热议问题