例如,如果我有一个像这样定义的函数:
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);
函数之前,我正试图找出一种检查方法:
$('a[href="#prestador"]').on('show.bs.tab',function (e) {
$("#nota_prestador").jsGrid("destroy");
createGrid('nota_prestador',data,'CPF/CNPJ TOMADOR');
});
}
这可行吗?
答案 0 :(得分:3)
您可以通过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