簡體   English   中英

將對象轉換為數組的優雅方式

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

假設我有一個返回數組或值的函數:

const a = f(...);
// a === [ 1 ];

const b = f(...);
// b = 1;

將返回值轉換為數組的最優雅的方法是什么,以便a === b

我希望像[ ...b ]這樣的東西會起作用,但它拋出了。 我到目前為止的解決方案是Array.isArray(b) ? b : [ b ] Array.isArray(b) ? b : [ b ] ,但我很好奇是否有更簡潔的方法來做到這一點,最好是單個函數/非分支表達式

你可以做

return [b].flat()

函數Array.prototype.concat接受一個數組或單個值作為參數。

這是假設您總是想要一個數組

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

也許出路是使用構造

Array.from()

例子:

Array.from(a());

Array.from(b());

兩者都應該以數組形式返回結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM