Javascript func的參數給預設值的問題今天又碰到一次

發現有很好的解法,轉自http://blog.wu-boy.com/2009/11/25/1861/

--

在網路上看到一篇:『Setting default values for missing parameters in a Javascript function』,提到在 Javascript 函式參數如果未定義,就會出現 undefine 的錯誤訊息,請看底下範例:

function foo(a, b, c) {
    document.write('a: ' + a + ' ');
    document.write('b: ' + b + ' ');
    document.write('c: ' + c + ' ');
    document.write('<br />');
}

測試函數:

foo();
foo(1);
foo(1, 2);
foo(1, 2, 3);

輸出結果:

a: undefined b: undefined c: undefined
a: 1 b: undefined c: undefined
a: 1 b: 2 c: undefined
a: 1 b: 2 c: 3

底下有兩種方式可以解決此問題:

1. 加入 if 判斷:

function foo(a, b, c) {

    if(typeof a == 'undefined') {
        a = 'AAA';
    }
    if(typeof b == 'undefined') {
        b = 'BBB';
    }
    if(typeof c == 'undefined') {
        c = 'CCC';
    }

    document.write('a: ' + a + ' ');
    document.write('b: ' + b + ' ');
    document.write('c: ' + c + ' ');
    document.write('<br />');

}

測試:

foo();
foo(1);
foo(1, 2);
foo(1, 2, 3);

結果輸出:

a: AAA b: BBB c: CCC
a: 1 b: BBB c: CCC
a: 1 b: 2 c: CCC
a: 1 b: 2 c: 3

2. 網友提供的最佳解法:

function foo(a, b, c) {

    a = a || "AAA";
    b = b || "BBB";
    c = c || "CCC";

    document.write('a: ' + a + ' ');
    document.write('b: ' + b + ' ');
    document.write('c: ' + c + ' ');
    document.write('<br />');

}

假設 a 尚未被定義,就會以 AAA 預設值顯示,程式碼也相當好閱讀。

--

arrow
arrow
    全站熱搜

    dizzy03 發表在 痞客邦 留言(0) 人氣()