2010-09-07 21 views
3

在PHP中,我們可以指定變量的默認值在像功能:功能和不必需的變量

function myFunction(myDefaultVariable, myOtherVariable, myCheckVariable = "basic"){ 
    // so yeah, myDefaultVariable is required always, 
    // same applies for myOtherVariable, 
    // and myCheckVariable can be skipped in function call, because it has a default value already specified. 
} 

有沒有類似這樣的東西在JavaScript?

回答

8

你不需要在Javascript中傳遞所有變量。

雖然少哈克的方式是使用對象:

function foo(args) { 
    var text = args.text || 'Bar'; 

    alert(text); 
} 

要叫它:

foo({ text: 'Hello' }); // will alert "Hello" 
foo(); // will alert "Bar" as it was assigned if args.text was null 
+0

你基本上是傳遞一個參數:與對應於「參數的屬性的對象,做我的理解對不對 – Piskvor 2010-09-07 07:30:00

+0

啊,謝謝正是我一直在尋找 – jolt 2010-09-07 07:30:18

+0

@Piskvor - 是正確的嗎?!。它的一個參數包含了你可以訪問的屬性,其中任何一個都可以爲null,所以它的重要性在於檢查而不是假定它們已經被指定。通常,對於'mandatory'參數,我檢查它們是否在頂部提供該方法拋出一個異常,如果不是這樣的話。'if(!('參數'在args中))拋出('參數是一個必需的參數');' – 2010-09-07 07:34:07

4

不完全是,但你可以通過檢查這個值是通過模擬它和設置默認,例如

optionalArg = (typeof optionalArg == "undefined")?'defaultValue':optionalArg 

注意像這樣的技術的原理,即使optionalArg供應,但計算結果爲假的 - 這就像optionalArg=optionalArg || 'default'一個簡單的成語失敗上。

同樣在每個函數中,您都可以訪問一個名爲arguments的數組,該數組將包含傳遞給該函數的所有參數,您可以使用它來使用具有可變長度參數列表的函數。

1

沒有我知道的:

但是有兩種方法可以解決這個問題。

//1. function.arguments - this is advisable if you don't know the 
// maximum number of passed arguments. 

function foo() { 
    var argv = foo.arguments; 
    var argc = argv.length; 
    for (var i = 0; i < argc; i++) { 
    alert("Argument " + i + " = " + argv[i]); 
    } 
} 

foo('hello', 'world'); 

//2. "Or" operator - this is good for functions where you know the 
// details of the optional variable(s). 

function foo (word1, word2) { 
    word2 = word2 || 'world'; 
    alert (word1 + ' ' + word2); 
} 

foo ('hello'); // Alerts "hello world"