2014-02-20 30 views
0

我用arguments,允許在一個函數的多個參數,如:的Javascript多個參數和不同的數據類型的功能

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

傳遞foo(1, 2, 3, 4) = OK

但我需要知道,如果它是可以使用各種類型的參數,如foo(1, "b", 3, "d")。當我嘗試時,我得到Value is not what was expected

有什麼建議嗎?

+0

是的,通過不同的類型是完全正常的,並且當你傳遞'(1,「b」,3,「d」)'時,你發佈的代碼不會產生任何錯誤。 – Pointy

+0

它在這裏工作得很好。你能提供一種方法來重現你的問題嗎? – Tibos

+2

它的工作見http://jsfiddle.net/LKZkH/ – Satpal

回答

1

你需要在你foo功能,如果你希望一個function作爲第一argument自己處理這一點,例如,你需要檢查它是否是,在第一次的foo

if(typeof arguments[0] != "function") 
    throw new Error("unexpected argument") 

,或者如果您需要number作爲第一個參數:

if(typeof arguments[0] != "number") 
    throw new Error("unexpected argument") 

或嘗試將其先轉換爲數字,如:

var o = parseInt(arguments[0]) 
if(Number.isNaN(o)) 
    throw new Error("unexpected argument") 
0

而且添加,來區分你的函數參數實實在在地建之間的JavaScript對象類(日期,數組,正則表達式等)是使用比較像:

Object.prototype.toString.call(arguments[0]) === '[object Date]' 
Object.prototype.toString.call(arguments[0]) === '[object RegExp]' 

等,使用類似於@ am1r_5h的答案

相關問題