admin管理员组

文章数量:1290157

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.

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);

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.

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. 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)?

Note

  • I can't change the code of getListOfItemsFromServiceA.
Share Improve this question asked Jul 14, 2017 at 14:43 Ala Eddine JEBALIAla Eddine JEBALI 7,8919 gold badges51 silver badges71 bronze badges 1
  • why you don't want to add if condition? – error404 Commented Jul 14, 2017 at 14:50
Add a ment  | 

2 Answers 2

Reset to default 8

Do this:

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

You can add a fallback if exampleResult is 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.

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);

本文标签: JavaScript Array destructuring assignment and null valueStack Overflow