ES6/2015 中的空安全属性访问(和条件赋值) [英] Null-safe property access (and conditional assignment) in ES6/2015
问题描述
在 ES6 (ES2015/JavaScript.next/Harmony) 中是否有类似 的
<例如 CoffeeScript 中的/strong> ?还是计划用于 ES7?null
安全的属性访问(null 传播/存在)操作符?.
Is there a null
-safe property access (null propagation / existence) operator in ES6 (ES2015/JavaScript.next/Harmony) like ?.
in CoffeeScript for example? Or is it planned for ES7?
var aThing = getSomething()
...
aThing = possiblyNull?.thing
大致如下:
if (possiblyNull != null) aThing = possiblyNull.thing
理想情况下,如果 possivelyNull
是 null
aThing
>
Ideally the solution should not assign (even undefined
) to aThing
if possiblyNull
is null
推荐答案
更新 (2020-01-31):似乎人们还在发现这个,这是当前的故事:
Update (2020-01-31): Seems people are still finding this, here's the current story:
- 可选链规范(第 4 阶段):https://github.com/tc39/proposal-可选链
- babel-preset-env:这可能就是你想要的 https://babeljs.io/docs/en/babel-preset-env
- Babel v7 插件:https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining
更新 (2017-08-01):如果你想使用官方插件,你可以尝试使用新转换的 Babel 7 的 alpha 版本.您的里程可能会有所不同
Update (2017-08-01): If you want to use an official plugin, you can try the alpha build of Babel 7 with the new transform. Your mileage may vary
https://www.npmjs.com/package/babel-插件转换可选链
原文:
目前处于第 1 阶段的功能:可选链.
A feature that accomplishes that is currently in stage 1: Optional Chaining.
https://github.com/tc39/proposal-optional-chaining
如果你今天想使用它,有一个 Babel 插件可以实现这一点.
If you want to use it today, there is a Babel plugin that accomplishes that.
https://github.com/davidyaha/ecmascript-optionals-proposal
这篇关于ES6/2015 中的空安全属性访问(和条件赋值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!