2011-12-21 81 views

回答

2

這在這裏不少詳細討論:http://www.wirfs-brock.com/allen/posts/166。提出解決問題的對策,隨着明顯

a.map(function(e) { return parseInt(e, 10)}) 

還包括數構造:

a.map(Number) 

或解決方案基於部分應用程序(見http://msdn.microsoft.com/en-us/scriptjunkie/gg575560更多):

Function.prototype.partial = function(/*args*/) { 
    var a = [].slice.call(arguments, 0), f = this; 
    return function() { 
     var b = [].slice.call(arguments, 0); 
     return f.apply(this, a.map(function(e) { 
      return e === undefined ? b.shift() : e; 
     })); 
    } 
}; 

["1", "2", "08"].map(parseInt.partial(undefined, 10)) 
8

.map呼叫parseInt()與參數 - 值和數組索引:

parseInt('1', 0); // OK - gives 1 
parseInt('2', 1); // FAIL - 1 isn't a legal radix 
parseInt('3', 2); // FAIL - 3 isn't legal in base 2 
+0

謝謝!還有一個JavaScript陷阱。 – georg 2011-12-21 18:45:55

+1

如果你沒有閱讀手冊,這只是一個陷阱... – Alnitak 2011-12-21 18:54:24

+1

記錄的疑難雜症,又名反直覺行爲,仍然是一個難題。請閱讀:http://www.wirfs-brock.com/allen/posts/166 – georg 2011-12-21 19:02:40

3

.map使用三個參數調用parseInt() - 值,數組索引和整個數組實例。