简单的方式来插入JavaScript数组中所有元素之间的元素?

编程入门 行业动态 更新时间:2024-10-19 04:31:22
本文介绍了简单的方式来插入JavaScript数组中所有元素之间的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 说我有一个数组 var arr = [1,2,3] ,我想用元素分隔每个元素,例如。 var sep =&,所以输出是 [1,&,2,&,3] code>。

另一种想法的方法是我想做Array.prototype.join( arr.join(sep) ),而没有结果是一个字符串(因为我想要使用的元素和分隔符是对象,而不是字符串)。

是否有功能/漂亮/优雅的方式来做这个在es6 / 7或lodash没有任何感觉笨拙的东西像:

_。 (arr.map((el,i)=> [el,i< arr.length-1?sep:null]))//太复杂

_。flatten(arr.map(el => ; [el,sep])。slice(0,-1)// extra sep added,memory wasted

甚至

arr.reduce((prev,curr)=> {prev.push(curr,sep);返回上一个;},[])。slice(0,-1) //可能是三个中最好的,但是我必须做一个地图已经 //,我还是一样问题如前两个 - //内联三元或片

编辑: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指出有用的泛化,输入可以是任何可迭代的。 >

如果你不喜欢使用生成器,那么

[]。 (... a.map(e => ['&',e]))slice(1)

Say I have an array var arr = [1, 2, 3], and I want to separate each element by an element eg. var sep = "&", so the output is [1, "&", 2, "&", 3].

Another way to think about it is I want to do Array.prototype.join (arr.join(sep)) without the result being a string (because the elements and separator I am trying to use are Objects, not strings).

Is there a functional/nice/elegant way to do this in either es6/7 or lodash without something that feels clunky like:

_.flatten(arr.map((el, i) => [el, i < arr.length-1 ? sep : null])) // too complex

or

_.flatten(arr.map(el => [el, sep]).slice(0,-1) // extra sep added, memory wasted

or even

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

Edit: Haskell has this function, called intersperse

解决方案

Using a generator:

function *intersperse(a, delim) { let first = true; for (const x of a) { if (!first) yield delim; first = false; yield x; } } console.log([...intersperse(array, '&')]);

Thanks to @Bergi for pointing out the useful generalization that the input could be any iterable.

If you don't like using generators, then

[].concat(...a.map(e => ['&', e])).slice(1)

更多推荐

简单的方式来插入JavaScript数组中所有元素之间的元素?

本文发布于:2023-10-24 20:02:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524868.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   组中   简单   方式   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!