Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

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

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'].map(String.prototype.trim);

...but my console said...

TypeError: String.prototype.trim called on null or undefined

jsFiddle.

I can't see any null or undefined values in my array.

String.prototype.trim() and Array.prototype.map() are defined in Chrome 17, which I'm using to test.

Why doesn't this work? I get the feeling I have overlooked something obvious.

I realise I could loop or drop a function in there. That's not the point of this question, however.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...