我将举例解释:

猫王运算符(?:)

“猫王运算符”是缩写 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';

其他回答

对于前者,您可以使用||。Javascript的“逻辑或”操作符,不是简单地返回罐装的真值和假值,而是遵循这样的规则:如果左参数为真,则返回左参数,否则计算并返回右参数。当你只对真值感兴趣时,结果是一样的,但这也意味着foo || bar || baz返回包含真值的foo, bar或baz中最左边的一个。

但是,您将找不到一个可以区分false和null的值,并且0和空字符串是假值,因此避免使用value ||默认构造,其中value可以合法地为0或""。

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

这是一个有趣的解决方案,安全导航操作员使用一些mixin..

http://jsfiddle.net/avernet/npcmv/

  // Assume you have the following data structure
  var companies = {
      orbeon: {
          cfo: "Erik",
          cto: "Alex"
      }
  };

  // Extend Underscore.js
  _.mixin({ 
      // Safe navigation
      attr: function(obj, name) { return obj == null ? obj : obj[name]; },
      // So we can chain console.log
      log: function(obj) { console.log(obj); }
  });

  // Shortcut, 'cause I'm lazy
  var C = _(companies).chain();

  // Simple case: returns Erik
  C.attr("orbeon").attr("cfo").log();
  // Simple case too, no CEO in Orbeon, returns undefined
  C.attr("orbeon").attr("ceo").log();
  // IBM unknown, but doesn't lead to an error, returns undefined
  C.attr("ibm").attr("ceo").log();

我认为下面是相当于安全导航的操作符,虽然有点长:

var streetName = user && user.address && user.address.street;

streetName将是user.address.street或undefined的值。

如果你想让它默认为其他东西,你可以结合上面的快捷方式或给出:

var streetName = (user && user.address && user.address.street) || "Unknown Street";

目前有一个规范草案:

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