Let's say I have a function that returns either an array or a value:
const a = f(...);
// a === [ 1 ];
const b = f(...);
// b = 1;
What is the most elegant way to transform the returned value into an array, so that a === b
?
I was hoping something like [ ...b ]
would work, but it throws. The solution I have come to so far is Array.isArray(b) ? b : [ b ]
Array.isArray(b) ? b : [ b ]
, but I'm curious if there's a cleaner way to do this, preferably a single function/non-branching expression
你可以做
return [b].flat()
The function Array.prototype.concat
accepts either an array or a single value as a parameter.
This is assuming you want an array always .
//This is just to illustrate. const f = (asArray) => asArray ? [1] : 1, a = [].concat(f(true)), b = [].concat(f(false)); console.log(a.length === b.length && a[0] === b[0]);
Perhaps a way out is to use the construct
Array.from()
Example:
Array.from(a());
and
Array.from(b());
Both should return you the result in an array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.