简体   繁体   English

JavaScript数组解构分配和空值

[英]JavaScript Array destructuring assignment and null value

I'm using an external service getListOfItemsFromServiceA which accepts an id (of user) and returns a list of 5 items (exactly 5) associated to this user. 我正在使用外部服务getListOfItemsFromServiceA ,该服务接受(用户的) id ,并返回与该用户相关的5个项目(恰好是5个)的列表。

I used Array destructuring assignment to set the value of those items which is working fine like this (just an example): 我使用数组解构分配来设置这些项的值,这些项的工作原理如下:

 var item1, item2, item3, item4, item5; //var result = getListOfItemsFromServiceA(1622); var exampleResult = ['item1', 'item2', 'item3', 'item4', 'item5']; [item1, item2, item3, item4, item5] = exampleResult; console.log(item1, item2, item3, item4, item5); 

The problem I have is that in some cases getListOfItemsFromServiceA(id) returns null for example when the id is not found in the database. 我的问题是,在某些情况下,例如在数据库中找不到id时, getListOfItemsFromServiceA(id)返回null So my code is not working: 所以我的代码不起作用:

 var item1, item2, item3, item4, item5; //var result = getListOfItemsFromServiceA(1622); var exampleResult = null; [item1, item2, item3, item4, item5] = exampleResult; console.log(item1, item2, item3, item4, item5); 

Is there a way to solve this using Array destructing syntax instead of adding an if condition like if(getListOfItemsFromServiceA(1622) !== null) ? 有没有一种方法可以使用数组破坏语法来解决此问题,而不是添加诸如if(getListOfItemsFromServiceA(1622) !== null)类的if条件?

Note 注意

  • I can't change the code of getListOfItemsFromServiceA . 我无法更改getListOfItemsFromServiceA的代码。

做这个:

[item1, item2, item3, item4, item5] = exampleResult || [];

You can add a fallback if exampleResult is null : 如果exam​​pleResult为null,则可以添加回退:

 var item1, item2, item3, item4, item5; var exampleResult = null; [item1, item2, item3, item4, item5] = exampleResult || []; console.log(item1, item2, item3, item4, item5); 

This produces undefined, undefined, undefined, undefined, undefined . 这将产生undefined, undefined, undefined, undefined, undefined

You can also set default values to the destructured variables : 您还可以将默认值设置为非结构化变量:

 var item1, item2, item3, item4, item5; var exampleResult = null; [item1="", item2="", item3="", item4="", item5=""] = exampleResult || []; console.log(item1, item2, item3, item4, item5); 

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

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