【问题标题】:check if variables are undefined检查变量是否未定义
【发布时间】:2018-09-09 22:29:50
【问题描述】:

是否有可能有一个函数来检查提供给它的任何参数是否未定义?我正在尝试以下方法

function isDefined() {
    for (var i = 0; i < arguments.length; i++)
        if (typeof (arguments[i]) === "undefined") return false;
    return true;
}

但是,如果我传递一个未定义的参数,它会给我一个错误:

Uncaught ReferenceError: b is not defined

更新

示例用法:

let a = 5;
let c = "hello";

isDefined(a, b, c); // gives false
isDefined(a, c); // gives true

【问题讨论】:

  • 参数在函数被调用之前被评估。该函数无法及时返回并防止出现此错误。
  • 做 if(!arguments[i]) return false
  • @ManosKounelakis 这有什么帮助?它只是将参数转换为布尔值
  • 你可以这样写let isDefined = function(){ return [...arguments].some(arg=&gt;!arg)}
  • 此错误仅在函数未声明时发生。如果你声明了变量,你不应该得到一个错误。

标签: javascript function undefined-reference


【解决方案1】:
function isDefined() {
    return !Array.from(arguments).includes(undefined);
}

【讨论】:

    【解决方案2】:

    我看到它工作的唯一方法是如果你将 isDefined 包装在 try/catch 中。您的示例用法必须修改如下:

    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)}`);

    【讨论】:

    • 但这仅适用于您将 b 定义为 b = undefined 的情况。如果 b 从未被分配,这不会检查
    • 我的意思是连let d都没有
    • 我唯一能想到的就是在 try catch 中运行 isDefined。
    【解决方案3】:

    undefined 的值为 null。 数组中任何未定义的元素都返回 null。

    function isDefined() {
        for (var i = 0; i < arguments.length; i++)
            if (arguments[i]==null) return false;
        return true;
    }
    

    【讨论】:

    • 这不会解决操作问题
    • undefined 和 null 是两个不同的东西。作为证据,你可以做undefined === null,你会发现它是假的。
    • === 与 == 不同,undefined === null 返回 false,undefined == null 返回 true。三等式更严格。
    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 2019-05-11
    • 2012-04-28
    • 2015-05-01
    • 1970-01-01
    • 2016-07-02
    相关资源
    最近更新 更多