在ES6 (ES2015/JavaScript.next/Harmony)中是否有一个空安全的属性访问(空传播/存在)操作符?比如CoffeeScript ?还是计划在ES7中?

var aThing = getSomething()
...
aThing = possiblyNull?.thing

大致如下:

if (possiblyNull != null) aThing = possiblyNull.thing

理想情况下,解决方案不应该分配(甚至未定义)一个东西,如果posblynull是空的


当前回答

香草替代安全的财产访问

(((a.b || {}).c || {}).d || {}).e

最简洁的条件赋值可能是这样的

try { b = a.b.c.d.e } catch(e) {}

其他回答

根据这里的列表,目前还没有建议将安全遍历添加到Ecmascript中。所以不仅没有很好的方法,而且在可预见的将来也不会加入。

编辑:由于这篇文章最初是我写的,所以它实际上是被添加到语言中的。


// The code for the regex isn't great, 
// but it suffices for most use cases.

/**
 * Gets the value at `path` of `object`.
 * If the resolved value is `undefined`,
 * or the property does not exist (set param has: true),
 * the `defaultValue` is returned in its place.
 *
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @param {*} [def] The value returned for `undefined` resolved values.
 * @param {boolean} [has] Return property instead of default value if key exists.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = { 'a': [{ 'b': { 'c': 3 } }], b: {'c-[d.e]': 1}, c: { d: undefined, e: 0 } };
 *
 * dotGet(object, 'a[0].b.c');
 * // => 3
 * 
 * dotGet(object, ['a', '0', 'b', 'c']);
 * // => 3
 *
 * dotGet(object, ['b', 'c-[d.e]']);
 * // => 1
 *
 * dotGet(object, 'c.d', 'default value');
 * // => 'default value'
 *
 * dotGet(object, 'c.d', 'default value', true);
 * // => undefined
 *
 * dotGet(object, 'c.d.e', 'default value');
 * // => 'default value'
 *
 * dotGet(object, 'c.d.e', 'default value', true);
 * // => 'default value'
 *
 * dotGet(object, 'c.e') || 5; // non-true default value
 * // => 5 
 * 
 */
var dotGet = function (obj, path, def, has) {
    return (typeof path === 'string' ? path.split(/[\.\[\]\'\"]/) : path)
    .filter(function (p) { return 0 === p ? true : p; })
    .reduce(function (o, p) {
        return typeof o === 'object' ? ((
            has ? o.hasOwnProperty(p) : o[p] !== undefined
        ) ? o[p] : def) : def;
    }, obj);
}

不。你可以在JavaScript中使用lodash#get或类似的东西。

// Typescript
static nullsafe<T, R>(instance: T, func: (T) => R): R {
    return func(instance)
}

// Javascript
function nullsafe(instance, func) {
    return func(instance);
};

// use like this
const instance = getSomething();
let thing = nullsafe(instance, t => t.thing0.thing1.thingx);

更新(2022-01-13):似乎人们仍在发现这一点,以下是目前的情况:

可选链接现在在规范(ES2020)中,并且被所有现代浏览器支持,更多的在存档建议中:https://github.com/tc39/proposal-optional-chaining 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版本。你的里程可能会有所不同

https://www.npmjs.com/package/babel-plugin-transform-optional-chaining

原:

实现这一功能的功能目前处于阶段1:可选链接。

https://github.com/tc39/proposal-optional-chaining

如果你现在就想使用它,有一个Babel插件可以实现这一点。

https://github.com/davidyaha/ecmascript-optionals-proposal