简体   繁体   English

将对象转换为数组的优雅方式

[英]Elegant way to transform an object to an array

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 ?将返回值转换为数组的最优雅的方法是什么,以便a === b

I was hoping something like [ ...b ] would work, but it throws.我希望像[ ...b ]这样的东西会起作用,但它抛出了。 The solution I have come to so far is Array.isArray(b) ? b : [ b ]我到目前为止的解决方案是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 Array.isArray(b) ? b : [ b ] ,但我很好奇是否有更简洁的方法来做到这一点,最好是单个函数/非分支表达式

你可以做

return [b].flat()

The function Array.prototype.concat accepts either an array or a single value as a parameter.函数Array.prototype.concat接受一个数组或单个值作为参数。

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.两者都应该以数组形式返回结果。

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

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