[英]Writing a function with variable number of input arguments
I have a javascript function whose number of input arguments is not known ( has variable number of arguments) and it has also an input dictionary argument called "kwargs" argument which can have some other arguments as (key,value), like this:
function plot( data, kwargs={}){
}
I want to get both the "name" and "value" of the arguments in the body of the function when I call the function with a number of arguments. 假設我想要像這樣調用 function:
plot(lines, xlabel="Project",
ylabel="Investor",
xfmt="%", xscale=100, yfmt="%.", yscale=100)
我想在 function 定義中獲得“xlable”、“Project”、“ylabel”、“Investor”、“xfmt”、“%”等(可能還有更多參數)。
我該如何寫'情節' function def?
function plot( data, kwargs={},...restArguments){
}
然后您可以通過 restArguments 數組獲取值,但您無法獲取 arguments 的名稱。
由於 JavaScript 不支持命名 arguments,因此您最好的選擇是使用下面描述的字典方法來處理變量參數。
你可以:
arguments
object 。 這適用於每個版本的 ECMAScript。arguments
方法。請注意,如果不進行一些重構,您將無法使用方法 2 和 3。
以object為參數,使用屬性為實際參數。 這樣,您可以(某種程度上)通過它們的標識符來引用它們。
這將使:
function aFunc(aVar, anotherVar, aThirdVar) {
console.log(aVar, anotherVar, aThirdVar);
}
對此:
function aFunc(data) {
console.log(data.aVar, data.anotherVar, data.aThirdVar);
}
新的 function 可以這樣調用:
aFunc({aVar: 5, anotherVar: 10, aThirdVar: 20}); // Works
// -- or --
// Note the un-ordered properties
aFunc({aThirdVar: 20, aVar: 5, anotherVar: 10}); // Also works
但是,這會帶來以下問題:
data.var ||= 'fallback-value';
.使用這種方法的優點是:
arguments
object 由於arguments
存在於所有版本的 ECMAScript 中,因此當目標是(相當多的)向后兼容性時,我會推薦這種方法。
arguments
is present in any function execution context, meaning in both function declarations as well as function expressions , however not in arrow-function (lambda) expressions (added in ES6; for ES6 usage, using the Rest Parameter-syntax is recommended anyway).
使用它,您可以使用 function 的參數以及訪問 function 的參數列表中未列出的任何其他參數。
采用可變數量 arguments 的函數應具有名為 var_args 的最后一個參數。 您可能不會在代碼中引用 var_args; 使用 arguments 陣列。
請注意,僅僅因為谷歌這樣做並不意味着這是一個人應該編碼的方式。 它只是在處理 Google 代碼時如何編碼的指南(。)。
以下是遵循 Google 風格指南的示例:
function aFunc(first, second, var_args) {
console.log(first, second, arguments[2], arguments[3]);
}
aFunc(5, 10, 20); // => '5 10 20 undefined'
ES6 中引入了 Rest 參數語法和箭頭函數 (lambda) 表達式。
由於建議使用此方法而不是使用arguments
object,因此在決定使用兩者中的哪一個時,應嘗試實施此方法,因為訪問其余參數更直觀,它也適用於箭頭函數表達式,並且 Z55276C10D84E1DF7713B441E 參數為一個實際的數組。
因為 Rest 參數是一個實際的數組,所以可以使用擴展語法以及Array
繼承的任何功能,這與arguments
object 不同。
這是一個類似於arguments
對象方法的示例,現在使用 Rest 參數語法代替:
function aFunc(first, second, ...rest) {
console.log(first, second, rest[0], rest[1]);
}
aFunc(5, 10, 20);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.