ES6 / 2015中的无安全属性访问(和有条件分配) [英] Null-safe property access (and conditional assignment) in ES6/2015
问题描述
在ES6(ES2015 / JavaScript.next / Harmony)中有 null
-safe属性访问(空传播/存在)运算符,如 <$ c $例如, CoffeeScript 中的c>?。 还是计划用于ES7?
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
理想情况下,如果 possibleNull,则解决方案不应该分配(甚至
是 undefined
)到 aThing
null
Ideally the solution should not assign (even undefined
) to aThing
if possiblyNull
is null
推荐答案
目前处于第1阶段的完成:无效传播。
A feature that accomplishes that is currently in stage 1: Null Propagation.
https://github.com/tc39/proposals
您可以在这里查看:
https://github.com/claudepache/es-optional-chaining
https://docs.google.com/presentation/d/11O_wIBBbZgE1bMVRJI8kGnmC6dWCBOwutbN9SWOK0fU/view
如果你想使用它今天,有一个Babel插件来实现。
If you want to use it today, there is a Babel plugin that accomplishes that.
https://github.com/davidyaha/ecmascript-optionals-proposal
更新(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-plugin-transform-optional-chaining
这篇关于ES6 / 2015中的无安全属性访问(和有条件分配)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!