空条件运算符

Ian*_*Ian 57 javascript

C#6.0刚刚发布,并且有一个新的不错的小功能,我真的很想在JavaScript中使用它.他们被称为Null条件运算符.这些使用?.?[]语法.

这些操作基本上允许您null在尝试访问属性之前检查您获得的对象.如果对象是null,那么您将获得null属性访问的结果.

int? length = customers?.Length;
Run Code Online (Sandbox Code Playgroud)

所以这里int可以为null,并且如果customers为null 则将采用该值.更好的是你可以链接这些:

int? length = customers?.orders?.Length;
Run Code Online (Sandbox Code Playgroud)

我不相信我们可以用JavaScript做到这一点,但我想知道做类似事情的最好方法是什么.通常我发现链接if块难以阅读:

var length = null;
if(customers && customers.orders) {
    length = customers.orders.length;
}
Run Code Online (Sandbox Code Playgroud)

小智 32

被称为"可选链接",它目前是第一阶段的TC39提案.一通天插件不过是在第7版已经上市.

用法示例:

const obj = {
  foo: {
    bar: {
      baz: 42,
    },
  },
};

const baz = obj?.foo?.bar?.baz; // 42

const safe = obj?.qux?.baz; // undefined
Run Code Online (Sandbox Code Playgroud)


Vla*_*lav 16

JS逻辑运算符返回没有truefalse,但truly还是falsy价值本身.例如在表达式中x && y,如果x是falsy,那么它将被返回,否则y将被返回.所以运算符的真值表是正确的.

在您的情况下,您可以使用表达式customers && customers.orders && customers.orders.Length获取length值或第falsy一个.

你也可以做一些魔术((customers || {}).orders || {}).length (个人而言,我不喜欢这种语法和可能的垃圾收集压力)

甚至使用maybemonad.

function Option(value) {
    this.value = value;
    this.hasValue = !!value;
}

Option.prototype.map = function(s) {
    return this.hasValue
        ? new Option(this.value[s])
        : this;
}

Option.prototype.valueOrNull = function() {
    return this.hasValue ? this.value : null;
}

var length = 
    new Option(customers)
        .map("orders")
        .map("length")
        .valueOrNull();
Run Code Online (Sandbox Code Playgroud)

它比以前的所有方法都要长,但是在没有任何魔力的情况下清楚地显示出你的意图.

  • 我认为最后应该是`((customers || {}).orders || []).length`(最后一个`||`之后的空数组). (2认同)

Mar*_*nze 6

有几种方法可以提高代码可读性(取决于您的需求):

  1. 您已经使用了(v7 或更高版本)并且您使用了“可选链接”babel 插件(完成的提案)(或只是preset-stage-3):

    const length = customers?.orders?.Length;
    
    // With default value (otherwise it will be `undefined`):
    const length = customers?.orders?.Length || defaultLength;
    
    // File: .babelrc
    { "plugins": ["@babel/plugin-proposal-optional-chaining"] }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您已经在使用(v3.7 或更高版本):使用lodash.get方法:

    var length = _.get(customers, 'orders.length');
    
    // With default value (otherwise it will be `undefined`):
    var length = _.get(customers, 'orders.length', defaultLength);
    
    Run Code Online (Sandbox Code Playgroud)
  3. 普通的javascript:

    var length = customers && customers.orders && customers.orders.length;
    
    // With default value (otherwise it may be whatever falsy value "customers" or "customers.orders" might have):
    var length = (customers
        && customers.orders
        && customers.orders.length) || defaultLength;
    
    Run Code Online (Sandbox Code Playgroud)