我将举例解释:

猫王运算符(?:)

“猫王运算符”是缩写 Java的三元运算符。一个 这很方便的例子是 返回一个“合理的默认值” 如果表达式解析为false或 null。一个简单的例子是这样的 这样的:

def gender = user.male ? "male" : "female"  //traditional ternary operator usage

def displayName = user.name ?: "Anonymous"  //more compact Elvis operator

安全导航操作员(?.) 使用安全导航操作符 来避免NullPointerException。 通常当你有一个参考 您可能需要验证的对象 在访问前它不是空的 对象的方法或属性。 为了避免这种情况,安全航行 运算符将简单地返回null 而不是抛出异常,比如 所以:

def user = User.find( "admin" )           //this might be null if 'admin' does not exist
def streetName = user?.address?.street    //streetName will be null if user or user.address is null - no NPE thrown

当前回答

我创建了一个软件包,使它更容易使用。

NPM jsdig Github jsdig

你可以处理简单的东西,比如and object:

const world = {
  locations: {
    europe: 'Munich',
    usa: 'Indianapolis'
  }
};

world.dig('locations', 'usa');
// => 'Indianapolis'

world.dig('locations', 'asia', 'japan');
// => 'null'

或者更复杂一点:

const germany = () => 'germany';
const world = [0, 1, { location: { europe: germany } }, 3];
world.dig(2, 'location', 'europe') === germany;
world.dig(2, 'location', 'europe')() === 'germany';

其他回答

我创建了一个软件包,使它更容易使用。

NPM jsdig Github jsdig

你可以处理简单的东西,比如and object:

const world = {
  locations: {
    europe: 'Munich',
    usa: 'Indianapolis'
  }
};

world.dig('locations', 'usa');
// => 'Indianapolis'

world.dig('locations', 'asia', 'japan');
// => 'null'

或者更复杂一点:

const germany = () => 'germany';
const world = [0, 1, { location: { europe: germany } }, 3];
world.dig(2, 'location', 'europe') === germany;
world.dig(2, 'location', 'europe')() === 'germany';

这通常被称为空合并运算符。Javascript没有。

Javascript的逻辑OR运算符短路,可以取代你的“猫王”运算符:

var displayName = user.name || "Anonymous";

然而,据我所知,没有与你的?相当的。操作符。

这是一个简单的猫王运算符等价:

function elvis(object, path) {
    return path ? path.split('.').reduce(function (nestedObject, key) {
        return nestedObject && nestedObject[key];
    }, object) : object;
}

> var o = { a: { b: 2 }, c: 3 };
> elvis(o)

{ a: { b: 2 }, c: 3 }

> elvis(o, 'a');

{ b: 2 }

> elvis(o, 'a.b');

2

> elvis(o, 'x');

undefined

目前有一个规范草案:

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

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

现在,我喜欢使用lodash get(object, path [,defaultValue])或dlv delve(obj, keypath)

更新(截至2019年12月23日):

可选链接已经移动到阶段4