在ES6 (ES2015/JavaScript.next/Harmony)中是否有一个空安全的属性访问(空传播/存在)操作符?比如CoffeeScript ?还是计划在ES7中?
var aThing = getSomething()
...
aThing = possiblyNull?.thing
大致如下:
if (possiblyNull != null) aThing = possiblyNull.thing
理想情况下,解决方案不应该分配(甚至未定义)一个东西,如果posblynull是空的
它不像?那样好。运算符,但要实现类似的结果,你可以这样做:
user && user.address && user.address.postcode
因为null和undefined都是假值(参见参考),所以只有当前面的属性不是null或undefined时,才会访问&&运算符后面的属性。
或者,你可以这样写一个函数:
function _try(func, fallbackValue) {
try {
var value = func();
return (value === null || value === undefined) ? fallbackValue : value;
} catch (e) {
return fallbackValue;
}
}
用法:
_try(() => user.address.postcode) // return postcode or undefined
或者,使用回退值:
_try(() => user.address.postcode, "none") // return postcode or a custom string