2016-11-14 92 views
0

我有一個名爲test的函數,它接受兩個參數。如果任何通過任何輸入到該功能,它的作品完美。但我有一個場景,可能會有輸入,也可能不會。如何處理這種情況。有沒有可能在node.js中做?我嘗試使用typeof檢查,但它沒有按預期工作。如何處理函數中的可選參數

function test(input, callback) { 
    if (input) { 
     callback(input) 
    } 
    else { 
     callback("No input") 
    } 
} 
test("message", function (result) { 
    console.log(result) 
}) 
test(function (result) { // This scenario fails 
    console.log(result) 
}) 
+1

您對輸入檢查兩個論點。 – Teemu

+0

@RobG我已經提到了鏈接http://stackoverflow.com/questions/148901/is-there-a-better-way-to-do-optional-function-parameters-in-javascript。但我可以將第二個參數作爲可選參數的示例。在我的情況下,第二個參數是必需的或必需的param – user4324324

回答

0

可以檢查typeof輸入,如果它是一個功能

function test(input, callback) { 
    let input = input; 
    let cb = callback; 

    if (typeof input === 'function') { 
     cb = input; 
     input = 'some value'; 
    } 

    cb(input); 
} 

test("message", function (result) { 
    console.log(result) 
}) 


test(function (result) { // This scenario fails 
    console.log(result) 
}) 
0

你可以只傳遞一個null作爲像這樣的參數:

test(null, function (result) { 
    console.log(result) 
}) 
+0

有沒有更好的方法來做到這一點? – user4324324

+0

根據您問題中的有限信息,不可能知道什麼會更好地滿足您的需求。 – Esko