簡體   English   中英

將單個值轉換為數組

[英]Turning a single value into an array

在我的項目中,我經常發現自己檢查一個值是否為數組。

如果該值不是數組,我會從中創建一個單元素數組。

如果值為undefinednull ,我將創建一個空數組。

該值本身通常是對象數組或單個 object 或undefined

const array = value ? (Array.isArray(value) ? value: [value]) : [];

在我決定將其納入單獨的 util function 之前,是否有更簡潔的方法(可能使用lodashunderscore )?

你可以做

var eventsArray = events ? [].concat(events) : [];

.concat()函數同時接受數組和單個參數,因此無論哪種方式最終都可以得到所需的結果。

由於您在代碼中使用const,因此我假設您使用的是ES2015 / ES6。 ES1015的默認函數參數允許在未傳遞任何值或未定義的情況下,使用默認值初始化形式參數。

function abc(value = []) {

  const array =  Array.isArray(value) ? value: [value];

}

這是使用lodash的castArrayisNil封裝在mixin中的解決方案:

_.mixin( {'asArray' : function(value){
    return _.isNil(value) ? [] : _.castArray(value);
}});

用法:

_.asArray(null)      -> []
_.asArray(undefined) -> []
_.asArray(0)         -> [0]
_.asArray(false)     -> [false]
_.asArray([1,2,3])   -> [1,2,3]
_.asArray('wibble')  -> ['wibble']

如果使用ES6,則可以執行以下操作,它比.concat()更干凈;

function method(value = []) {
  const array = [...value];
}

確保變量是數組的一種精簡 ES2020 方法:

value = [].concat(value ?? [])

解釋

正如@VoteyDisciple 解釋的那樣, concat function將連接單個值或 arrays 值。 如果左側的值為 null 或未定義,則空值合並運算符 (??)將使用右側的值(第二個空數組)。 所以如果 value 是 null,它會將一個空數組連接到一個空數組,返回一個空數組。

例子

// Different inputs and outputs
values = [].concat([1,2,3] ?? [])   // [1,2,3]
values = [].concat(1 ?? [])         // [1]
values = [].concat(null ?? [])      // []

// Wrap it in a function if you like
function array(value) {
    return [].concat(value ?? [])
}

// Use it like this
values = array(values)

// Or even like this
for (let value of array(values)) {
    console.log(value)
}

使用.flat()的更短解決方案

如果您不必檢查undefinednull值,還有一種更巧妙的方法。 如果之前不是數組,這基本上會將值轉換為 singleton 數組。

[value].flat()

用法示例

[12].flat() // Output: [12]
[[[12]]].flat() // Output: [[12]]

刪除空值

如果你想刪除空值 - 只需在其上添加一個過濾器。 這將刪除所有虛假的值。

[value].filter(x => x).flat()

陷阱

由於0 (和false )是一個虛假值,如果您將數字存儲在數組中,建議將數組值與nullundefined進行顯式比較。

[value].filter(x => x !== null && x !== undefined).flat()

為了稍微縮短它,我們可以使用 Lodash 的isNil方法。

[value].filter(_.isNil).flat()

暫無
暫無

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

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