2015-09-14 51 views

回答

2

這是part of ES6,但截至目前,not widely supported所以你可以做這樣的事情

jm.toInt = function(num, base) { 
 
    return parseInt(num, arguments.length > 1 ? base : 10); 
 
}

+0

使用'arguments.length> 1?'有什麼好處,而不是簡單的'base?' –

+0

@AlexandruSeverin無...你可以使用上面的任何一個格式在這種情況下.... –

3

ofcourse還有一個辦法!

function myFunc(x,y) 
{ 
    x = typeof x !== 'undefined' ? x : 1; 
    y = typeof y !== 'undefined' ? y : 'default value of y'; 
    ... 
} 

你的情況

jm.toInt = function(num, base){ 
     return parseInt(num, arguments.length > 1 ? base: 'default value'); 
    } 
4

隨着邏輯或,默認值是可能的。

jm.toInt = function (num, base) { 
    return parseInt(num, base || 10); 
} 
0

使用typeof,以驗證參數存在(括號內添加,使其更易於閱讀):

jm.toInt = function (num, base) { 
    var _base = (typeof base === 'undefined') ? 10 : base 
    return parseInt(num, _base); 
}