简体   繁体   English

有没有办法在javascript中使用Array.splice,第三个参数作为数组?

[英]Is there a way to use Array.splice in javascript with the third parameter as an array?

I'm attempting the following: 我正在尝试以下方法:

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]

I am confined in my use case by having a2 exist as an array of indeterminant size. 通过将a2作为不确定大小的数组存在,我被限制在我的用例中。 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. 我知道我可以迭代a2的元素并一次一个地拼接它们,但我更喜欢最快的方法,因为我需要做很多事情。

Array.splice supports multiple arguments after the first two. Array.splice在前两个之后支持多个参数。 Those arguments will all be added to the array. 这些参数都将添加到数组中。 Knowing this, you can use Function.apply to pass the array as the arguments list. 知道这一点,您可以使用Function.apply将数组作为参数列表传递。

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));

With ES6, you can use the spread operator. 使用ES6,您可以使用扩展运算符。 It makes it much more concise and readable. 它使它更简洁和可读。

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

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

a1.splice(1, 0, a2);

var flatten = [].concat.apply([], a1); // ["a", "b", "c", "d", "e", "f"]

This should do the trick. 这应该可以解决问题。

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

a1.concat(a2, a1.splice(1,a1.length-1)) // [a, b, c, d, e, f]

Try this: 试试这个:

var params = a2.slice(0);
params.unshift(1,0);
a1.splice.apply(a1,params);

In the more general case: 在更一般的情况下:

Array.prototype.splice_multi = function(offset,todelete,insert) {
    var params = insert.slice(0);
    params.unshift(offset,todelete);
    return this.splice.apply(this,params);
};
a1.splice_multi(1,0,a2);
Array.prototype.splice.apply( [1,2,3], [2, 0].concat([4,5,6]) );
private moveElements(source: Array<any>, target: Array<any>) {
    target.push(...source);
    source.splice(0, source.length);
    //or
    [].push.apply(target,source);
    source.splice(0, source.length);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM