是否有可能具有检查提供给其的任何参数是否不确定的函数?我正在尝试以下
function isDefined() {
for (var i = 0; i < arguments.length; i++)
if (typeof (arguments[i]) === "undefined") return false;
return true;
}
但是,如果我通过一个未定义的参数,这给了我一个错误:
未介绍的参考文献:b未定义
update
示例用法:
let a = 5;
let c = "hello";
isDefined(a, b, c); // gives false
isDefined(a, c); // gives true
function isDefined() {
return !Array.from(arguments).includes(undefined);
}
我看到的唯一方法是,如果您将其包装在尝试/捕获中。您的示例用法必须进行修改如下:
let a = 5;
let c = "hello";
try{
isDefined(a, b, c); // gives false
}catch(e){
// ... some code that can return false
}
try{
isDefined(a, c); // gives true
}catch(e){
// ... some code
}
这是一个工作示例:
let a = 5;
// b isn't a thing
let c = 'hello';
let d = null;
let e;
function isDefined() {
!arguments;
for (arg in arguments) {
if(arguments[arg] === null || arguments[arg] === undefined) {
return false;
}
}
return true;
}
console.log(`isDefined(a, c): Result: ${isDefined(a, c)}`);
//you'd have to wrap isDefined in a try/catch if you're checking for this
try{
console.log(`try{isDefined(a, b, c)}catch(e){...}: Result: ${isDefined(a, b, c)}`);
}catch(err){
console.log('try{isDefined(a, b, c)}catch(e){...}: Result: false');
}
console.log(`isDefined(d) Result: ${isDefined(d)}`);
console.log(`isDefined(e): Result: ${isDefined(e)}`);
未定义的值null。数组返回null中的任何未定义元素。
function isDefined() {
for (var i = 0; i < arguments.length; i++)
if (arguments[i]==null) return false;
return true;
}