2010-12-09 69 views
0

我有以下功能:通逗號分隔的參數js函數

function calculateAspect(options){ 
    def = { 
     orgw: 0, 
     orgh: 0, 
     tarw: 0, 
     tarh: 0 
    }; 
    o = $.extend(def,options); 
    console.log(o); 


};  
calculateAspect({orgw:640}); 

,我希望能夠通過IT價值像以下:

calculatedAspect(640,480,320) 

calculateAspect(200) 

鑑於功能,這可能看起來不合邏輯。但我只是好奇如何把它關掉。

+0

我可能是錯的,但我認爲你必須通過它的陣列,或者你的論點直接申報。 – 2010-12-09 16:10:08

+0

你想通過傳遞參數的那些數字發生什麼? – RoToRa 2010-12-09 16:15:28

回答

2

您可以使用arguments包含所有傳遞的參數:

function calculateAspect(options){ 
    var argNames = ["orgw","orgh","tarw","tarh"]; 
    def = { 
     orgw: 0, 
     orgh: 0, 
     tarw: 0, 
     tarh: 0 
    }; 
    for (var i=0, n=Math.min(arguments.length, 4); i<n; i++) { 
     def[argNames[i]] = arguments[i]; 
    } 
    console.log(o); 
} 
1

你不得不彌補自己約定的參數應該是什麼意思,但你可以做這樣的事情:

function calculateAspect(orgw, orgh, tarw, tarh) { 
    var def = { /* ... */ }; 
    if (arguments.length === 1 && (typeof orgw) === "object") { 
    var o = $.extend(def, orgw); 
    // ... normal code ... 
    } 
    else { 
    calculateAspect({orgw: orgw, orgh: orgh, tarw: tarw, tarh: tarh}); 
    } 
} 

可能。