即使看起來有限,也是一個非常有用的對象。例如,您可以製作接受可變數量參數的功能。格式函數,在迪恩·愛德華茲(Dean Edwards)的base2庫中找到,演示了此靈活性:
>您提供一個模板字符串,其中您使用%1至%9添加了值的值,然後提供多達9個代表要插入字符串的其他參數。例如:
>將其轉換為真實數組
function format(string) { var args = arguments; var pattern = new RegExp("%([1-" + arguments.length + "])", "g"); return String(string).replace(pattern, function(match, index) { return args[index]; }); };
參數對象允許我們執行各種JavaScript技巧。這是MakeFunc函數的定義。此功能使您可以為該功能提供功能參考和任何數量的參數。它將返回一個匿名函數,該函數調用您指定的函數,並在調用匿名函數時提供預設參數與提供的任何新參數一起提供: 應用程序的第一個參數是指該函數將被調用;基本上,這將引用所調用函數的關鍵字。目前,這有點先進,所以我們將其保持無效。第二個參數是一個值數組,將轉換為該函數的參數對象。 makefunc將原始值的原始數組連接到提供給匿名函數的一系列參數上,並將其提供給所謂的函數。 >說,在模板始終相同的情況下,您需要輸出一條消息。為了使您避免每次調用格式函數時都必須引用模板,您可以使用MakeFunc Utility函數返回將為您調用格式並自動填寫模板參數的函數: >您可以像這樣重複調用Majortom函數: >每次調用Majortom函數時,都會使用第一個參數(已填寫的模板)調用格式函數。
函數convertargstoArray(){ //或 您可以使用“ typeof”操作員檢查傳遞給函數的每個參數的類型。以下是一個示例: >>} } } } } } } }使用預設參數創建函數
function format(string) {
var args = arguments;
var pattern = new RegExp("%([1-" + arguments.length + "])", "g");
return String(string).replace(pattern, function(match, index) {
return args[index];
});
};
format("And the %1 want to know whose %2 you %3", "papers", "shirt", "wear");
var args = Array.prototype.slice.call(arguments);
function makeFunc() {
var args = Array.prototype.slice.call(arguments);
var func = args.shift();
return function() {
return func.apply(null, args.concat(Array.prototype.slice.call(arguments)));
};
}
var majorTom = makeFunc(format, "This is Major Tom to ground control. I'm %1.");
majorTom("stepping through the door");
majorTom("floating in a most peculiar way");
"This is Major Tom to ground control. I'm stepping through the door."
"This is Major Tom to ground control. I'm floating in a most peculiar way."
repeat is a function that takes a function reference, and 2 numbers. The first number is how many times to call the function and the second represents the delay, in milliseconds, between each call. Here's the definition for repeat:
function format(string) {
var args = arguments;
var pattern = new RegExp("%([1-" + arguments.length + "])", "g");
return String(string).replace(pattern, function(match, index) {
return args[index];
});
};
經常詢問有關JavaScript參數的問題
> JavaScript中的“參數”對像是什麼?它包含一個類似數組的結構,所有參數傳遞給了函數。當函數需要處理可變數量的參數時,此對像很有用。重要的是要注意,“參數”對像不是一個實際的數組,但是如果需要的話,它可以轉換為一個。但是,您可以使用array.from()方法或傳播操作員(…)將其轉換為數組。以下是一個示例:
//或
//或
var argsArray = [... gruments];
>}
}
}
} 函數checkArgStype(){
>(var i = 0; i
第一個參數傳遞給函數。同樣,“參數[1]”是指第二個論點,依此類推。如果沒有傳遞參數,則“參數[0]”將是“未定義的”。
我可以在JavaScript中修改“參數”對象?但是,通常不建議這樣做,因為它可能導致令人困惑和難以刪除的代碼。在嚴格的模式下,任何修改“參數”對象的嘗試都會丟棄錯誤。
>
“參數”對象的長度屬性是什麼?
>>我可以在JavaScript中使用默認參數的“參數”對象?如果調用具有默認參數的函數的參數少於參數,則“參數”對象僅包含傳遞的實際參數,而不包含默認值。此屬性被棄用,不應在新代碼中使用。相反,您可以使用命名函數表達式或箭頭函數。
以上是參數:JavaScript奇數的詳細內容。更多資訊請關注PHP中文網其他相關文章!