有没有在JavaScript中的第三个参数作为数组使用方法Array.splice的方法吗? [英] Is there a way to use Array.splice in javascript with the third parameter as an array?

查看:421
本文介绍了有没有在JavaScript中的第三个参数作为数组使用方法Array.splice的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以下内容:

var a1 = ['a', 'e', 'f'];  // [a, e, f]
var a2 = ['b', 'c', 'd'];  // [b, c, d]
a1.splice(1, 0, a2);       // expected [a, b, c, d, e, f]
                           // actual (a, [b, c, d], e, f]

我对有A2存在不确定的作为大小的数组限制在我的使用情况。有谁知道的方式来养活拼接数组作为替代,或者一个内置功能来做到这一点?我知道我可以遍历的A2的元素,并在同一时间拼接它们之一,但我preFER最快速的方法,因为我需要做很多。

I am confined in my use case by having a2 exist as an array of indeterminant size. Does anyone know of a way to feed splice an array as the substitution, or alternatively a built-in function to do this? I know I could iterate over the elements of a2 and splice them in one at a time, but I'd prefer the fastest method possible because I will need to do this a lot.

推荐答案

方法Array.splice 支持前两个之后多个参数。这些参数将所有被添加到阵列。知道了这一点,你可以使用 Function.apply 来传递数组的参数列表。

Array.splice supports multiple arguments after the first two. Those arguments will all be added to the array. Knowing this, you can use Function.apply to pass the array as the arguments list.

var a1 = ['a', 'e', 'f'];
var a2 = ['b', 'c', 'd'];

// You need to append `[1,0]` so that the 1st 2 arguments to splice are sent
Array.prototype.splice.apply(a1, [1,0].concat(a2));

这篇关于有没有在JavaScript中的第三个参数作为数组使用方法Array.splice的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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