ciqulover
ciqulover

Reputation: 13

Error when trim each string in an array

If I trim each string in an array,

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

It works.

But [' a ',' b','c '].map(''.trim.call) will cause Uncaught TypeError: undefined is not a function.

I thought it should work...?

Upvotes: 1

Views: 48

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You need to bind call to String.prototyp.trim

[' a ','  b','c  '].map(''.trim.call.bind(''.trim))

[' a ','  b','c  '].map(Function.prototype.call.bind(''.trim))

Right now you simply get Function.prototype.call and then invoke it with undefined context

const call = Function.prototyp.call

[' a ','  b','c  '].map(call) 

So each step is just call(item, index, array) while call uses this

Upvotes: 2

Related Questions