Why won't passing `''.trim()` straight to `[].map()`'s callback work?

后端 未结 4 1931
南笙
南笙 2020-12-05 18:04

I have an array of strings. I want to trim each string in the array.

I thought using [].map() with \'\'.trim() would work...

[\' a\', \' b   \', \'c         


        
相关标签:
4条回答
  • 2020-12-05 18:32

    What @Slace says is the right explanation. @ThomasEding's answer also works but has one terrible inefficieny that it may create functions within a loop, which is not a good thing to do.

    Another way of doing would be (reference here):

    [' a', ' b   ', 'c'].map(Function.prototype.call, String.prototype.trim);  
    // gives ["a", "b", "c"]
    

    Standard browser disclaimer: This will work wherever Function.prototype.call and String.prototype.trim will work and for older browsers, you can easily substitute trim with a polyfill like this:

    if(!String.prototype.trim) {  
      String.prototype.trim = function () {  
        return this.replace(/^\s+|\s+$/g,'');  
      };  
    }
    

    Update: Interstingly, while this works fastest in Chrome, @ThomasEding's method runs slightly faster in IE10 and FF20 - http://jsperf.com/native-trim-vs-regex-trim-vs-mixed

    0 讨论(0)
  • 2020-12-05 18:36

    That's because trim is not being called with the proper this context. Remember that this is dynamically bound in JS. You will have to create a wrapper to pass to trim to properly bind this:

    [' a', ' b   ', 'c'].map(function (str) {
      return str.trim();
    });
    
    0 讨论(0)
  • 2020-12-05 18:38

    With ES6 syntax it can be as easy as this:

    [' hello  ', '  world'].map(str => str.trim());
    
    0 讨论(0)
  • 2020-12-05 18:44

    trim is on the String prototype, meaning that it expects the this context to be that of a string where as the map method on Array provides the current array item as the first argument and the this context being the global object.

    0 讨论(0)
提交回复
热议问题