在JavaScript中是否可能内联检查空值?

68

我有一个函数,它解析了Google地图API的地址组件,然后返回城市/地点/路线名称。

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检查值是否仅为undefined、null或false]的重复问题(https://dev59.com/1Ww15IYBdhLWcg3wFHzf)。 - Mackija
getAddressComponent是异步的吗? - mplungjan
1
你是指 (element != null ? element.value.long_name : null) 吗? - GalAbra
@mplungjan 不,不是这样的。 - darkermuffin
@GalAbra 不,我的意思是我是否可以像这样做一些事情 https://tc39.github.io/proposal-optional-chaining/ - darkermuffin
@JennyO'Reilly 抱歉,它返回 null。 - darkermuffin
8个回答

134

2020的答案,它存在了!!!

现在您可以直接使用?.内联测试是否存在。 它被称为可选链式运算符,受到所有现代浏览器的支持。

如果属性存在,则继续进行下一个检查,或返回该值。 任何失败都会立即短路并返回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

?. 浏览器支持 - 94%,Oct '22

?? 浏览器支持 - 94%

Node 支持 - v14+


1
遗憾的是,您不能执行 ?? throw new Error("...") - Jeroen

30

2020更新

这个备受期待的特性现在已经在JavaScript中可用了!

我将重定向到Gibolt's answer,它很好地涵盖了它。

原始2018年答案

  • 在JavaScript(EcmaScript 5或6)中不存在"null-safe导航运算符",如C#、Angular模板等中的?. (有时写作?:时也称为Elvis运算符),至少目前还没有,不幸的是。

  • 你可以使用三元操作符?:在单行中测试null并返回一些依赖表达式,就像其他答案中已经给出的一样:

(使用 === null 仅检查null值,使用 == null 检查nullundefined

    console.log(myVar == null ? myVar.myProp : 'fallBackValue');
  • 在某些情况下,比如你的情况,当你的变量应该保存一个object时,你可以简单地利用任何对象为真值而nullundefined为假值的事实:

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

你可以使用 !! 将值转换为布尔类型来检测假值,并将其嵌入行内代码:

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

但是,要非常小心使用这个“falsy测试”,因为如果您的变量是0''NaN,则它也是“falsy”的,尽管它不是null/undefined。


10

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

return num || 0;

从今天起,更加符合语义:

return num ?? 0


你想要实现什么目标?假设num是int类型,那么return num || 0等同于return num... - Sebastian Nielsen
1
问题标签是JavaScript和null。我不会假设它是int :) - ilkerkaran

4
let component = getAddressComponent(addressComponents, 'route');
let route = component ? component : null

你可以使用 ? 运算符来检查值是否为 truefalse,然后在 JavaScript 中设置该值。 null 将被视为 false

3
你需要的是一个空值合并运算符。JavaScript 没有这个运算符。大多数情况下,人们使用逻辑或 || 来实现此目的,但它在属性访问上不起作用。
有一个提案将 null 合并添加到语言中,但还没有完成: 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
但我强烈建议你不要这样做:这可能永远不会成为语言的一部分,而你的代码库中将存在无效代码。

3

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

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

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

关于你问到的?,它是条件(三元)运算符,语法为条件 ? 如果为真 : 如果为假,你可以按照以下方式使用:

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'));


请注意,“空字符串”与“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')); - Pac0

0

.? 不能在 JavaScript 中使用,你可以考虑使用 TypeScript。

例如,你可以使用 try...catch 结构:

let route

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

0
作为对jeroen的回答:
你不能?? throw new Error("...")。但是你可以这样做:

const throwError = (missingParam) => { throw new Error(`Parameter ${missingParam} is missing`); };

{
    someParam: a.anotherParam ?? throwError('anotherParam')
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接