是否可以在javascript中检查null内联?
我有一个函数,可以解析Google Maps API JSON
的地址部分,然后返回城市/地区/路线名称.
I have a function which parses the address components of the Google Maps API JSON
and then returns the city / locality / route name.
getAddressComponent()
如果找不到密钥,则返回 null
.
The getAddressComponent()
returns a null
if it cannot find the key.
让route = getAddressComponent(addressComponents,'route').value.long_name;
因此,假设它没有找到密钥,然后我得到一个 Error:TypeError:显然因为未定义,所以无法读取未定义的属性'long_name'
.
So let's say it didn't find the key, then I get a Error: TypeError: Cannot read property 'long_name' of undefined
obviously because it's not defined.
除了条件方法(a === null)
之外,如何在javascript中检查 null
?
How do I check for null
in javascript other than the conditional method (a === null)
?
如何简单地通过进行这样的检查?
安全导航操作员
让route = getAddressComponent(addressComponents,'route')?. value.long_name;
如果不存在,则可能将 route
设置为 null
,而不是抛出错误?
And if it doesn't exists, it could probably set route
to null
instead of throwing a Error ?
2020年答案,存在!!
您现在可以直接使用?.
内联测试是否存在.它被称为 Optional Chaining Operator
(可选的链接运算符),所有现代浏览器均支持该功能.
2020 Answer, It Exists!!!
You can now directly use ?.
inline to test for existence. It is called the Optional Chaining Operator
, supported by all modern browsers.
如果存在一个属性,它将继续进行下一个检查,或返回该值.任何故障都会立即短路并返回 undefined
.
If a property exists, it proceeds to the next check, or returns the value. Any failure will immediately short-circuit and return 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
要确保默认定义的值,可以使用 ??
.如果需要第一个真实值,则可以使用 ||
.
To ensure a default defined value, you can use ??
. If you require the first truthy value, you can use ||
.
example?.c ?? "c" // "c"
example?.c || "c" // "c"
example?.a?.[2] ?? 2 // false
example?.a?.[2] || 2 // 2
如果不检查大小写,则必须存在left-side属性.如果没有,它将引发异常.
If you do not check a case, the left-side property must exist. If not, it will throw an exception.
example?.First // undefined
example?.First.Second // Uncaught TypeError: Cannot read property 'Second' of undefined
?.
浏览器支持-2021年3月89%
?.
Browser Support - 89%, Mar 2021
??
浏览器支持-89%
??
Browser Support - 89%
节点支持-v14 +