跳至內容
Astera Technology

函式預設參數只補 undefined,並非所有空值

沒傳值、undefined、null 和空字串,要分開試。

下載完整個案資料及參考答案 ↓

先追這段程式

title 函式用 Untitled 補上未傳或 undefined 的值。本例保留明確傳入的 null 和空字串,不自行改成標題。

完整原始程式
function title(value='Untitled'){return value;}
console.log(JSON.stringify([title(),title(undefined),title(null),title('')]));
確實的 console 輸出
["Untitled","Untitled",null,""]
值與執行位置
參數使用預設值傳回值
未傳會Untitled
undefined會Untitled
null不會null
""不會""

結果為何如此

預設值在呼叫時初始化,條件是參數值為 undefined,並非所有假值。??、|| 的補值界線各有不同,要先確定規則。

比較另一種寫法

value || Untitled 也會覆蓋 null 和刻意留空的文字,下面四種情況全被換成預設。

另開的有限例子
function title(value){return value||'Untitled';}
console.log(JSON.stringify([title(),title(undefined),title(null),title('')]));
另一寫法的輸出
["Untitled","Untitled","Untitled","Untitled"]

試清邊界

產生預設值時順便計次,原例四次呼叫會計到多少?

查看參考答案

兩次:未傳值及 undefined。null 和空字串不會執行預設初始化。

重新建立的邊界例子
let calls=0;function fallback(){calls++;return 'Untitled';}function title(value=fallback()){return value;}
const values=[title(),title(undefined),title(null),title('')];
console.log(JSON.stringify({values,calls}));
邊界例子的輸出
{"values":["Untitled","Untitled",null,""],"calls":2}

原始例子檔案