【问题标题】:Is it possible to check for null inline in javascript?是否可以在 javascript 中检查 null 内联?
【发布时间】:2018-06-28 17:45:40
【问题描述】:

我有一个函数可以解析 Google Maps API JSON 的地址组件,然后返回城市/地区/路线名称。

如果找不到密钥,getAddressComponent() 将返回 null

let route = getAddressComponent(addressComponents, 'route').value.long_name;

假设它没有找到密钥,那么我得到一个Error: TypeError: Cannot read property 'long_name' of undefined 显然是因为它没有定义。

除了条件方法(a === null)之外,如何在javascript中检查null

我怎样才能用?这样简单地检查

编辑:安全导航操作员

let route = getAddressComponent(addressComponents, 'route')?.value.long_name;

如果它不存在,它可能会将route 设置为null 而不是抛出错误?

【问题讨论】:

标签: javascript null


【解决方案1】:

2020 回答,它存在!!!

您现在可以直接使用?. inline 来测试是否存在。它被称为 Optional Chaining Operator,所有现代浏览器都支持。

如果属性存在,则继续进行下一次检查,或返回值。任何故障都会立即短路并返回undefined

const example = {a: ["first", {b:3}, false]}

example?.a  // ["first", {b:3}, false]
example?.b  // undefined

example?.a?.[0]     // "first"
example?.a?.[1]?.a  // undefined
example?.a?.[1]?.b  // 3

domElement?.parentElement?.children?.[3]?.nextElementSibling

为确保默认定义值,您可以使用??。如果需要第一个真值,可以使用||

example?.c ?? "c"  // "c"
example?.c || "c"  // "c"

example?.a?.[2] ?? 2  // false
example?.a?.[2] || 2  // 2

如果不检查大小写,则左侧属性必须存在。如果没有,它会抛出异常。

example?.First         // undefined
example?.First.Second  // Uncaught TypeError: Cannot read property 'Second' of undefined

?. Browser Support - 92%,2021 年 12 月

?? Browser Support - 92%

Node Support - v14+

【讨论】:

  • 很遗憾你做不到?? throw new Error("...")
【解决方案2】:

2020 年更新

这个期待已久的功能现在可以在 JavaScript 中使用了!

我会重定向到Gibolt's answer,这很好。

2018 年原始答案

  • Javascript 中没有“空安全导航运算符”(EcmaScript 5 或 6),如 C#、Angular 模板等中的 ?.(有时也称为 Elvis 运算符,在编写时?:) 不幸的是,至少现在还没有。

  • 您可以测试null 并在一行中返回一些依赖表达式使用三元运算符 ?:,正如其他答案中已经给出的那样:

(使用=== null 仅检查nulls 值,使用== null 检查null undefined

    console.log(myVar == null ? myVar.myProp : 'fallBackValue');
  • 在某些情况下,例如您的情况,当您的变量应该包含 object 时,您可以简单地使用任何对象都是 真实这一事实,而 @987654333 @ 和 undefinedfalsy 值:

      if (myVar) 
          console.log(myVar.myProp)
      else
          console.log('fallbackValue')
    

    您可以通过使用 !! 合并为布尔值来测试虚假值并将其设为内联:

      console.log(!!myVar ? myVar.myProp : 'fallbackValue');
    

    尽管使用这个“falsy test”要非常小心,因为如果你的变量是 0''NaN,那么它也是 falsy,即使它是不为空/未定义。

【讨论】:

    【解决方案3】:

    下面的代码为我简化了return num ? num : 0

    return num || 0;

    从今天开始在语义上更正确;

    return num ?? 0

    【讨论】:

    • 你想完成什么?假设 num 是 int 类型,那么 return num || 0 等价于 return num ...
    • 问题标签是javascript和null。我不会认为它是 int :)
    【解决方案4】:
    let component = getAddressComponent(addressComponents, 'route');
    let route = component ? component : null
    

    您可以使用? 运算符检查值是truefalse 然后在javascript 中设置值null 将是false

    【讨论】:

      【解决方案5】:

      你想要的是一个空合并运算符。 Javascript 没有。大多数情况下,人们为此目的使用逻辑 OR ||,但它不适用于属性访问。

      有人提议在语言中添加空值合并,但还差得很远: https://github.com/tc39/proposal-nullish-coalescing
      https://tc39.github.io/proposal-nullish-coalescing/

      如果你真的,真的,绝对想使用它,你可以使用这个 Babel 插件: https://www.npmjs.com/package/babel-plugin-transform-optional-chaining
      但我强烈建议您不要这样做:这可能永远不会成为该语言,并且您的代码库中会有无效代码。

      【讨论】:

        【解决方案6】:

        对于空字符串,您可以使用!:

        var foo = 'yo';
        console.log(!foo);
        
        var foo = null;
        console.log(!foo);

        而对于您询问的?,它是Conditional (ternary) Operator,语法是condition ? if true : if false,您可以按如下方式使用:

        var foo = 'yo';
        console.log('1 : ' + (!foo ? 'Null' : 'Not Null'));
        console.log('2 : ' + (foo === null ? 'Null' : 'Not Null'));
        console.log('3 : ' + (foo == null ? 'Null' : 'Not Null'));
        
        var foo = null;
        console.log('1 : ' + (!foo ? 'Null' : 'Not Null'));
        console.log('2 : ' + (foo === null ? 'Null' : 'Not Null'));
        console.log('3 : ' + (foo == null ? 'Null' : 'Not Null'));

        【讨论】:

        • 请注意,“空字符串”与“空值”不同,但它们在强制为布尔值时都是 falsy (例如当您应用 ! 时,或者在if)。 var foobar = ''; console.log((!foobar ? 'falsy like null' : 'not falsy')); console.log((foobar === null ? '===Null' : '!==Null')); console.log((foobar == null ? '==Null' : '!=Null'));.
        【解决方案7】:

        .? 不能在 javascript 中使用,为此,您可以查看 typescript。

        例如可以使用try...catch构造:

        let route
        
        try {
          route = getAddressComponent(addressComponents, 'route').value.long_name
        } catch (error) {
          route = null
        }
        

        【讨论】:

          猜你喜欢
          • 2023-04-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-02
          • 1970-01-01
          • 2011-01-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多