【问题标题】:Typescript: what's the difference between checking if a variable is empty vs. checking if it has a value?打字稿:检查变量是否为空与检查变量是否有值有什么区别?
【发布时间】:2021-06-11 01:27:47
【问题描述】:

我正在向我的代码添加验证,为了提高可读性,我写了以下代码:

  if (!uid) {
    return {result: 0, message: 'You are not authorized.'}
  }

替代方法是检查变量是否存在:

  if (uid) {
    //do some code
  }

但是,如果我有很多不同的变量要验证,我不喜欢像这样嵌套它们:

  if (uid) {
     if (otherVar) {
        //do some code 
     } else {
        //else code 1
     }
  } else {
     //else code 2
  }

方法一和方法二有区别吗?

【问题讨论】:

    标签: javascript typescript firebase google-cloud-functions


    【解决方案1】:

    答案:

    • 方法 1 仅检查该变量中的值。如果一个值存在/计算结果为true,那么它将返回true
    • 方法2在您完成第一次检查后检查变量,并返回true

    我的意见,您实际上不必那样做。相反,您可以使用 可选链接运算符 在对象内部进行安全检查。例如:

    const adventurer = {
      name: 'Alice',
      cat: {
        name: 'Dinah'
      }
    };
    
    const dogName = adventurer.dog?.name; // notice the usage of '?'
    console.log(dogName); // will return 'undefined' as 'dog' object does not exist in that object.
    

    引用 MDN 文档:

    ?.运算符的功能与 .链接运算符,除了如果引用为空(null 或未定义)而不是导致错误,表达式短路并返回未定义的值。与函数调用一起使用时,如果给定函数不存在,则返回 undefined。

    从那里,您可以使用可选链接来简化嵌套块 - 就像使用全局错误处理程序一样。

    const result = uid?.otherVar?; // imagine 'otherVar' does not exist!
    
    if (!result) return handleResult();
    

    进一步阅读:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-05
      • 2011-03-20
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多