Javascript - Array.map with String.trim

Why does the following not work? (Chrome, so no problem with missing Arrays.map)

[" a ", "b", " c", "d "].map(String.prototype.trim)

TypeError: String.prototype.trim called on null or undefined
+7
source share
4 answers

map passes each element of the array as a parameter to the function:

[element1, e2].map(myFunction); // --> myFunction(element1); myFunction(e2)

String.prototype.trimis not a function that you pass in the string to be trimmed. Instead, you call the function as a method of this line:

" some string ".trim(); // "some string"

To use trimin .map, you need to do something like:

[" a ", "b", " c", "d "].map(function(e){return e.trim();});
+15
source

In fact, since the function Array.map()must have currentElementas an argument, and String.prototype.trimdoes not accept any arguments, therefore, we cannot call it that way. So you have to make it hard:

[" a ", "b", " c", "d "].map(function(elem){
     return elem.trim();
});
+5
source

Ramda ( Javascript):

> var R = require('ramda')
undefined
> [" a ", "b", " c", "d "].map(R.trim)
[ 'a', 'b', 'c', 'd' ]

node repl.

+1
source

One shorter version with arrow function:

[" a ", "b", " c", "d "].map(e => e.trim());
+1
source

All Articles