【问题标题】:Whats the difference between the following conditions in TypeScript?TypeScript 中的以下条件有什么区别?
【发布时间】:2020-08-18 14:31:21
【问题描述】:
if (!value || value.length<1) 
if (value.length<1)

这两个条件有什么区别?不是一样吗?

【问题讨论】:

    标签: javascript arrays typescript conditional-statements truthiness


    【解决方案1】:

    快速理解的方法是您无法访问未定义数组的length 属性。所以第二个if 条件会抛出类似于Cannot access property 'length' of undefined 的错误。

    第一个if 条件会检查数组是否已定义。所以它不会抛出任何错误。

    Typescript 包含使用“安全导航运算符”或optional chaining operator?. 执行此检查的本机方式。所以在 TS 中,你可以简单地做

    if (value?.length < 1) { }
    

    相当于JS

    if ((value === null || value === void 0 ? void 0 : value.length) < 1) { }
    

    【讨论】:

      【解决方案2】:

      如果valuenullundefined,第二个if 将抛出一个错误,指出您无法访问null / undefined 中的length

      第一个阻止了这种情况,因为如果value 是真实的,它只会访问value.length。否则,第一个条件 (!value) 满足,所以第二个条件 (value.length &lt; 1) 甚至不会被评估。

      const arr1 = null;
      const arr2 = [];
      
      // Satisfies first condition:
      if (!arr1 || arr1.length < 1) console.log('No values in arr1.');
      
      // Satisfies second condition:
      if (!arr2 || arr2.length < 1) console.log('No values in arr2.');
      
      // Breaks:
      if (arr1.length < 1) console.log('No values in arr1.');

      不管怎样,这不是 TS 特有的,它只是 vanilla JS 的工作原理。

      【讨论】:

        【解决方案3】:

        不,它们完全不同。

        !value
        

        这会检查一个项目是否存在并且它不是未定义的,但![] and also ![3] 这总是错误的。基本上它会检查是否存在。

        甚至[] 总是正确的。

        length
        

        计算该数组内的元素个数,并将其纯粹应用于数组。

        [] , value.length&lt;1 this returns true.

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-02-14
          • 2014-03-21
          • 2019-01-12
          • 2020-07-11
          • 1970-01-01
          • 1970-01-01
          • 2013-12-02
          • 2018-06-07
          相关资源
          最近更新 更多