![](/img/trans.png)
[英]How to check if an argument/parameter is inside a const already defined on JavaScript?
[英]How to check if argument is defined in function definition in JavaScript?
例如,如果我有一個這樣定義的函數:
function set_name(name) {
return name;
}
但我這樣稱呼(出於個人原因):
set_name.apply(this, ['Duvdevan', 'Omerowitz']);
什么是最好的做法,以檢查和防止set_name
功能的進一步執行,如果它已經接受了超過1
參數/參數?
另外,我必須注意,在嘗試調用.apply
函數之前,我試圖找出一種檢查方法:
function set_name(name) {
// if(arguments.length > 1) console.log('This is not what I need though.');
return name;
}
var args = ['Duvdevan', 'Omerowitz'];
// Now, at this point I'd like to check if the set_name function can accept two arguments.
// If not, I'd console.log or return new Error here.
set_name.apply(this, args);
這可行嗎?
您可以通過Function.length
獲得函數期望的參數數量:
function set_name(name) { return name; } var args = ['Duvdevan', 'Omerowitz']; console.log(set_name.length); // 1 if (args.length > set_name.length) { throw new Error('Too many values'); // throws } set_name.apply(this, args); // not executed
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.