在JavaScript数组中所有元素之间穿插元素的方法是什么?

假设我有一个数组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

解决方法:

使用发电机:

function *intersperse(a, delim) {
  let first = true;
  for (const x of a) {
    if (!first) yield delim;
    first = false;
    yield x;
  }
}

console.log([...intersperse(array, '&')]);

感谢@Bergi指出输入可以是任何可迭代的有用概括.

如果你不喜欢使用发电机,那么

[].concat(...a.map(e => ['&', e])).slice(1)
上一篇:javascript – 数组转换/操作


下一篇:javascript – 递归地在深层嵌套对象的数组中查找对象