Javascript - 在另一个数组中插入一个数组 [英] Javascript - insert an array inside another array

查看:39
本文介绍了Javascript - 在另一个数组中插入一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在另一个数组中插入数组的更有效方法是什么.

What is the more efficient way to insert an array inside another array.

a1 = [1,2,3,4,5];
a2 = [21,22];

newArray - a1.insertAt(2,a2) -> [1,2, 21,22, 3,4,5];

如果 a2 数组很大,从性能的角度来看,使用 splice 迭代 a2 看起来有点可怕.

Iterating a2 using splice looks a bit awfull from a performance point of view if a2 array is large.

谢谢.

推荐答案

你可以使用 splice 结合一些 apply 技巧:

You can use splice combined with some apply trickery:

a1 = [1,2,3,4,5];
a2 = [21,22];

a1.splice.apply(a1, [2, 0].concat(a2));

console.log(a1); // [1, 2, 21, 22, 3, 4, 5];

在 ES2015+ 中,您可以使用扩展运算符来使这更好一些

In ES2015+, you could use the spread operator instead to make this a bit nicer

a1.splice(2, 0, ...a2);

这篇关于Javascript - 在另一个数组中插入一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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