Search

12/31/2013

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

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

String.prototype.mytrim = function (str) {return str.trim()} 
function (str) {return str.trim()}
[' ab'].map(String.prototype.trim)
TypeError: String.prototype.trim called on null or undefined
[' ab'].map(String.prototype.mytrim)
["ab"]
A JavaScript Optional Argument Hazard
Now look carefully at the specification of the map method. It refers to the function that is passed as the first argument to map as the callbackfn. The specification says, “the callbackfn is called with three arguments: the value of the element, the index of the element, and the object that is being traversed.” Read that carefully. It means that rather than three calls to parseInt that look like: parseInt("1") parseInt("2") parseInt("3") we are actually going to have three calls that look like: parseInt("1", 0, theArray); // returns 1 parseInt("2", 1, theArray); // returns NaN parseInt("3", 2, theArray); // returns NaN where theArray is the original array ["1","2","3"].

沒有留言: