【发布时间】:2016-09-04 20:19:50
【问题描述】:
假设我有一个数组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
【问题讨论】:
标签: javascript arrays ecmascript-6 lodash