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
.
- why you don't want to add if condition? – error404 Commented Jul 14, 2017 at 14:50
2 Answers
Reset to default 8Do 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
版权声明:本文标题:JavaScript Array destructuring assignment and null value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741495414a2381813.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论