Array.map and Javascript functions removed

How did

var a = "foo / bar/ baz ".split('/'); a.map( function (e) { return String.prototype.trim.call(e) } ) 

It works, but it doesn’t ...

 a.map( String.prototype.trim ); 
+1
javascript function ecmascript-5
source share
3 answers

Try the following:

 a.map(Function.prototype.call.bind(String.prototype.trim )) 

The reason this works, and just displaying String.prototype.trim does not work, because as others have pointed out, this will be undefined when a function tries to trim an array element. What this solution does is create a new function that takes this as the String.prototype.trim function. Since the new function is a modified version of Function.prototype.call , since map calls this function, passing it an array element, what essentially runs is: Function.prototype.call.call(String.prototype.trim, element) . This executes the String.prototype.trim function on the element passed in, and you get the result of the cutoff. This will also work:

  a.map(Function.call, "".trim) 

taking advantage of the fact that the second argument to map takes thisArg . For a little syntactic sugar, you can make a function that looks like this:

 Array.prototype.mapUsingThis = function(fn) { return this.map(Function.call, fn); }; 

Then you can just call

 a.mapUsingThis("".trim) 

.

+1
source share

String.prototype.trim is a non params function, it will be called by the string itself, but the map function requires func arg to accept str as params

0
source share

'this' refers to the string parameter in the first case, while in the second case, 'this' becomes undefined, since String.prototype.trim not bound to any object.

0
source share

All Articles