假设我有一个数组 var arr = [1, 2, 3]
,我想用一个元素(例如var sep = "&"
)分隔每个元素,使输出结果为[1, "&", 2, "&", 3]
。
另一种思考方式是,我想要执行 Array.prototype.join (arr.join(sep)
),但结果不应该是字符串(因为我尝试使用的元素和分隔符是对象,而不是字符串)。
在ES6/7或Lodash中是否有一种优美的方式来实现这一点,而无需使用像下面这样笨拙的方法:
_.flatten(arr.map((el, i) => [el, i < arr.length-1 ? sep : null])) // too complex
或者_.flatten(arr.map(el => [el, sep]).slice(0,-1) // extra sep added, memory wasted
甚至可以
arr.reduce((prev,curr) => { prev.push(curr, sep); return prev; }, []).slice(0,-1)
// probably the best out of the three, but I have to do a map already
// and I still have the same problem as the previous two - either
// inline ternary or slice
编辑:Haskell有一个名为intersperse的函数。
flatMap
使这个过程更加简单:a.flatMap(e => ['&', e]).slice(1)
。 其中,flatMap
会把每一个元素映射为一个数组,然后将这些数组拼接成一个新的数组。在这里,我们将每个元素e
映射为一个包含'&'
和e
的数组,然后取出从索引1开始的子数组,以去掉第一个无用的'&'
元素。 - baseten