具有阵列分度的阵列连接序列(“散布") [英] Join sequence of arrays with array delimeters ("intersperse")

查看:66
本文介绍了具有阵列分度的阵列连接序列(“散布")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有让我连接多个数组的函数,它们之间有定界符(定界符也是数组),类似于join的工作原理但不限于字符串?

Is there a function that lets me concat several arrays, with delimiters between them (the delimiters are also arrays), similarly to how join works but not restricted to strings?

该函数可以是标准JS或lodash之类的主要库的一部分(这就是为什么在标记中引用它的原因).

The function can be standard JS or part of a major library such as lodash (which is why it's referenced in the tags).

以下是用法示例:

let numbers = [[1], [2], [3]];
let result = _.joinArrays(numbers, [0]);
console.log(result); 
//printed: [1, 0, 2, 0, 3]

这类似于:

let strings = ["a", "b", "c"];
let result = strings.join(",");
console.log(result);
//printed: "a,b,c";

但是,join不能使用,因为它将值转换为字符串,我不想发生这种情况.

However, join can't be used because it turns values into strings, which I don't want to happen.

但是它适用于任何类型.

But it works for any type.

推荐答案

您可以简单地使用array.reduce连接数组,并推送您想用作分隔符的内容.

You could simply use array.reduce to concat the arrays, and push what ever you want to use as your delimiter.

let numbers = [[1], [2], [3]];

let n = numbers.reduce((a, b) => a.concat(0, b))

console.log(n)

这篇关于具有阵列分度的阵列连接序列(“散布")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆