我有一個名爲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)
})
您對輸入檢查兩個論點。 – Teemu
@RobG我已經提到了鏈接http://stackoverflow.com/questions/148901/is-there-a-better-way-to-do-optional-function-parameters-in-javascript。但我可以將第二個參數作爲可選參數的示例。在我的情況下,第二個參數是必需的或必需的param – user4324324