[英]check if variables are undefined
是否有可能檢查提供給它的參數是否未定義的函數? 我正在嘗試以下
function isDefined() {
for (var i = 0; i < arguments.length; i++)
if (typeof (arguments[i]) === "undefined") return false;
return true;
}
但是,如果傳遞未定義的參數,則會給我一個錯誤:
未捕獲的ReferenceError:未定義b
更新資料
用法示例:
let a = 5;
let c = "hello";
isDefined(a, b, c); // gives false
isDefined(a, c); // gives true
我看到它起作用的唯一方法是,如果在try / catch中包裝isDefined。 您的示例用法必須進行如下修改:
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)}`);
function isDefined() {
return !Array.from(arguments).includes(undefined);
}
undefined的值為null。 數組中所有未定義的元素都將返回null。
function isDefined() {
for (var i = 0; i < arguments.length; i++)
if (arguments[i]==null) return false;
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.