neuront neuront - 5 months ago 17
Javascript Question

Javascript - Apply trim function to each string in an array

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

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


['aa', 'bb']

My first trial is

It got "TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function" in chromium.

Then I tried { return String.prototype.trim.apply(s); });

It works. What's the difference?


String.prototype.trim.apply is the Function.prototype.apply method without being bound to trim. map will invoke it with the string, the index and the array as arguments and nothing (undefined) for the thisArg - however, apply expects to be called on functions:

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

What you can do is passing the trim function as the context for call:

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

What happens here is

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