想象一下,我有一個嵌套的數組結構。什麼是underscore.js相當於LINQ的SelectMany運算符?
var nested = [ [1], [2], [3] ];
使用underscore.js,我將如何生成一個扁平數組?
在C#中你可以使用Enumerable.SelectMany
這樣的:
var flattened = nested.SelectMany(item => item);
注意,在這種情況下,lambda直接選擇嵌套的項目,但它可能是任意表達式。
在jQuery中,它可能只使用:
var flattened = $.map(nested, function(item) { return item; });
但是這種方法沒有用下劃線的map功能工作。
那麼如何使用underscore.js得到扁平數組[1, 2, 3]
?
使用_.flatten? – yngccc
你也可以這樣寫:_.map(嵌套,函數(item){return item [0];}) – Darragh
@Darragh,這對我的具體示例有效,但不適用於子數組包含多個元素的情況。 –