简体   繁体   English

在多种条件下进行短路评估的最简洁方法

[英]Cleanest way to assign with short circuit evaluation on multiple conditions

I am trying to build a JSON object based on data that the client has on hand.我正在尝试根据客户端手头的数据构建一个 JSON 对象。

Ideally, it would select address data if available, then cart data if not available, otherwise null.理想情况下,如果可用,它将选择地址数据,如果不可用,则选择购物车数据,否则为 null。

Here the data is retrieved from localStorage, but I run into issues, addresses and cart resolve the following errors when null .这里的数据是从 localStorage 检索的,但我遇到了问题, addressescartnull时解决了以下错误。

Cannot read property 'length' of null无法读取 null 的属性“长度”

Cannot read property 'idShipTo' of undefined无法读取未定义的属性“idShipTo”

let cart = JSON.parse(localStorage.getItem('shopping-cart'));
let addresses = JSON.parse(localStorage.getItem('customer-address'));

this.request = {
  address: {
    shipToAddLine: addresses[0].shipToAddLine || cart.shipToAddLine || null,
    shipToCityStZip: addresses[0].shipToCityStZip || cart.shipToCityStZip || null
  }
}

I'd like to use something like the ternary operator, but use more than one if / else value.我想使用类似三元运算符的东西,但使用多个 if / else 值。

this.request = {
  address: {
    shipToAddLine: (addresses) ? addresses[0].shipToAddLine || (cart) ? cart.shipToAddLine || null,
    shipToCityStZip: (addresses) ? addresses[0].shipToCityStZip || (cart) ? cart.shipToCityStZip || null
  }
}

Is this possible using a clean (one-line) syntax in JS, or do I have to put the assignments in if / else blocks?这是否可以在 JS 中使用干净的(一行)语法,或者我是否必须将赋值放在 if / else 块中?

let shipToAddLine;
if (addresses) shipToAddLine = addresses[0].shipToAddLine;
else if (cart) shipToAddLine = cart.shipToCityStZip;
else shipToAddLine = null;

etc...等等...

您可以链接三元运算符

    shipToAddLine: addresses ? addresses[0].shipToAddLine : (cart ? cart.shipToAddLine : null),

You can use initialize it to appropriate empty values if not present如果不存在,您可以使用将其初始化为适当的空值

let cart = JSON.parse(localStorage.getItem('shopping-cart')) || {};
let addresses = JSON.parse(localStorage.getItem('customer-address')) || [{}];

this.request = {
  address: {
    shipToAddLine: addresses[0].shipToAddLine || cart.shipToAddLine || null,
    shipToCityStZip: addresses[0].shipToCityStZip || cart.shipToCityStZip || null
  }
}

If cart is null, it is initialized to an empty object and if address is null initially it is initialized to an array having an empty object.如果cart 为null,则将其初始化为空对象,如果address 最初为null,则将其初始化为具有空对象的数组。 Then you will not need checks before addresses[0].shipToAddLine and cart.shipToAddLine那么你将不需要在addresses[0].shipToAddLinecart.shipToAddLine之前检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM