1

我定義我的JavaScript函數如下:你如何處理多參數JavaScript函數?

function printCompanyName(company1, company2, company3, company4, company5) 
{ 
document.write("<p>" + company1 + "</p>"); 
document.write("<p>" + company2 + "</p>"); 
document.write("<p>" + company3 + "</p>"); 
document.write("<p>" + company4 + "</p>"); 
document.write("<p>" + company5 + "</p>"); 
} 

並把它稱爲如下:

printCompanyName("Dell, Microsoft, Apple, Gizmodo, Amazon"); 

但我得到以下輸出:

Dell, Microsoft, Apple, Gizmodo, Amazon 

undefined 

undefined 

undefined 

undefined 

是什麼給了!?我一直在想出這個問題。我想:

Dell 
Microsoft 
Apple 
Gizmodo 
Amazon 
+0

讓這個給你一個教訓!不要超過1小時,然後在stackoverflow上搜索,然後詢問。 – ChaosPandion 2010-02-08 02:45:46

回答

2

要撥打:

printCompanyName("Dell", "Microsoft", "Apple", "Gizmodo", "Amazon"); 

的方式你目前做你傳遞在一家公司「戴爾,微軟,蘋果,Gizmodo,亞馬遜」。

+0

非常感謝!你救了我的生命,因爲我即將接受它! – 2010-02-08 02:47:06

1

試試這個:

printCompanyName("Dell", "Microsoft", "Apple", "Gizmodo", "Amazon"); 
3

你傳遞,恰好包含4個逗號一個字符串。
因此,第一個參數包含該單個字符串,其他4個未定義。 (Sisnce你只給出了一個值)
由於Javascript參數是可選的,所以不會因爲不傳遞其他參數的值而導致錯誤。

您需要通過5名不同的字符串,它們之間用逗號,像這樣:

printCompanyName("Dell", "Microsoft", "Apple", "Gizmodo", "Amazon"); 
+1

+1作額外說明。 – ChaosPandion 2010-02-08 02:41:06

0

附加的信息:

使用的功能與作爲字符串逗號分隔的參數A的方法:

function printCompanyName(names) 
{ 
    // also check the type of names (you know "if it is a string object") 

    var data = names.split(',');  
    for(var i in data) { 
     document.write("<p>" + data[i].trim() + "</p>"); 
    } 
} 

爲例:printCompanyName("Dell, Microsoft, Apple, Gizmodo, Amazon");

否則使用內部參數變種的多參數函數:

function printCompanyName() 
{ 
    for(var i in arguments) { 
     document.write("<p>" + arguments[i] + "</p>"); 
    } 
} 

例:printCompanyName('Dell', 'Microsoft', 'Apple', 'Gizmodo', 'Amazon');就像SLaks說的那樣。