Javascript -在另一个数组中插入一个数组。

时间:2021-05-25 21:29:17

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

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

如果a2数组很大,那么从性能的角度来看,使用splice迭代a2看起来有点不太合适。

Thanks.

谢谢。

9 个解决方案

#1


122  

You can use splice combined with some apply trickery:

你可以使用splice和一些应用欺骗:

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

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

在ES2015+中,你可以使用扩展操作符来让它变得更好。

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

#2


11  

Had it wrong at first. Should have used concat() instead.

一开始是错的。应该用concat()代替。

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

var result = a1.slice( 0, 2 ).concat( a2 ).concat( a1.slice( 2 ) );

Example: http://jsfiddle.net/f3cae/1/

例如:http://jsfiddle.net/f3cae/1/

This takes a slice()[docs] of a1 up to the index, then does a concat()[docs] to add a2 to that array, then uses .concat() again taking another .slice() of a1, but this time starting at the same index through the end.

这将获取a1的一个slice()[docs]直到索引,然后执行concat()[docs]将a2添加到该数组中,然后使用.concat()再次获取a1的另一个.slice(),但这一次从最后的相同索引开始。

And add it to Array.prototype if you wish:

并添加到数组中。如果你希望原型:

Example: http://jsfiddle.net/f3cae/2/

例如:http://jsfiddle.net/f3cae/2/

Array.prototype.injectArray = function( idx, arr ) {
    return this.slice( 0, idx ).concat( arr ).concat( this.slice( idx ) );
};

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

var result = a1.injectArray( 2, a2 );

You can use the splice()[docs] method without iterating.

您可以使用splice()[docs]方法而不用迭代。

a1.splice( 2, 0, a2 );

http://jsfiddle.net/f3cae/

http://jsfiddle.net/f3cae/

#3


7  

You can now do this if using ES2015 or later:

如果使用ES2015或更高版本,您现在可以这样做:

var a1 = [1,2,3,4,5];
var a2 = [21,22];
a1.splice(2, 0, ...a2);
console.log(a1) // => [1,2,21,22,3,4,5]

Refer to this for documenation on the spread (...) operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

关于spread(…)操作符https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator的文档说明,请参阅本文

#4


2  

I wanted to find a way to do this with splice() and no iterating: http://jsfiddle.net/jfriend00/W9n27/.

我想找到一种使用splice()而不是迭代的方法:http://jsfiddle.net/jfriend00/W9n27/。

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

a2.unshift(2, 0);          // put first two params to splice onto front of array
a1.splice.apply(a1, a2);   // pass array as arguments parameter to splice
console.log(a1);           // [1, 2, 21, 22, 3, 4, 5];

In general purpose function form:

一般用途:

function arrayInsertAt(destArray, pos, arrayToInsert) {
    var args = [];
    args.push(pos);                           // where to insert
    args.push(0);                             // nothing to remove
    args = args.concat(arrayToInsert);        // add on array to insert
    destArray.splice.apply(destArray, args);  // splice it in
}

#5


1  

If you want to insert another array into an array without creating a new one, the easiest way is to use either push or unshift with apply

如果您想在不创建新数组的情况下向数组中插入另一个数组,最简单的方法是使用push或unshift with apply

Eg:

例如:

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

// Insert a1 at beginning of a2
a2.unshift.apply(a2,a1);
// Insert a1 at end of a2
a2.push.apply(a2,a1);

This works because both push and unshift take a variable number of arguments. A bonus, you can easily choose which end to attach the array from!

这是可行的,因为push和unshift都采用可变数量的参数。一个额外的好处是,您可以轻松地选择从哪个端附加数组!

#6


1  

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

扩展运算符允许在需要多个参数(用于函数调用)或多个元素(用于数组文本)的地方扩展表达式。

a2 = [21,22];
a1 = [1,2,...a2,3,4,5];//...a2 is use of spread operator
console.log(a1);

#7


0  

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

function injectAt(d, a1, a2) {
    for(var i=a1.length-1; i>=d; i--) {
        a1[i + a2.length] = a1[i];
    }
    for(var i=0; i<a2.length; i++) {
        a1[i+d] = a2[i];
    }
}

injectAt(2, a1, a2);

alert(a1);

#8


0  

Here's my version with no special tricks:

以下是我的版本,没有什么特别的技巧:

function insert_array(original_array, new_values, insert_index) {
    for (var i=0; i<new_values.length; i++) {
        original_array.splice((insert_index + i), 0, new_values[i]);
    }
    return original_array;
}

#9


0  

As mentioned in another thread,the answers above will not work in very large arrays (200K elements). See alternate answer here involving splice and manual push: https://*.com/a/41465578/1038326

正如在另一个线程中提到的,上面的答案不能在非常大的数组(200K元素)中工作。请参阅这里涉及到拼接和手动推送的替代答案:https://*.com/a/41465578/1038326

Array.prototype.spliceArray = function(index, insertedArray) {
    var postArray = this.splice(index);
    inPlacePush(this, insertedArray);
    inPlacePush(this, postArray);

    function inPlacePush(targetArray, pushedArray) {
  // Not using forEach for browser compatability
        var pushedArrayLength = pushedArray.length;
        for (var index = 0; index < pushedArrayLength; index++) {
           targetArray.push(pushedArray[index]);
       }
    }
}

#1


122  

You can use splice combined with some apply trickery:

你可以使用splice和一些应用欺骗:

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

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

在ES2015+中,你可以使用扩展操作符来让它变得更好。

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

#2


11  

Had it wrong at first. Should have used concat() instead.

一开始是错的。应该用concat()代替。

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

var result = a1.slice( 0, 2 ).concat( a2 ).concat( a1.slice( 2 ) );

Example: http://jsfiddle.net/f3cae/1/

例如:http://jsfiddle.net/f3cae/1/

This takes a slice()[docs] of a1 up to the index, then does a concat()[docs] to add a2 to that array, then uses .concat() again taking another .slice() of a1, but this time starting at the same index through the end.

这将获取a1的一个slice()[docs]直到索引,然后执行concat()[docs]将a2添加到该数组中,然后使用.concat()再次获取a1的另一个.slice(),但这一次从最后的相同索引开始。

And add it to Array.prototype if you wish:

并添加到数组中。如果你希望原型:

Example: http://jsfiddle.net/f3cae/2/

例如:http://jsfiddle.net/f3cae/2/

Array.prototype.injectArray = function( idx, arr ) {
    return this.slice( 0, idx ).concat( arr ).concat( this.slice( idx ) );
};

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

var result = a1.injectArray( 2, a2 );

You can use the splice()[docs] method without iterating.

您可以使用splice()[docs]方法而不用迭代。

a1.splice( 2, 0, a2 );

http://jsfiddle.net/f3cae/

http://jsfiddle.net/f3cae/

#3


7  

You can now do this if using ES2015 or later:

如果使用ES2015或更高版本,您现在可以这样做:

var a1 = [1,2,3,4,5];
var a2 = [21,22];
a1.splice(2, 0, ...a2);
console.log(a1) // => [1,2,21,22,3,4,5]

Refer to this for documenation on the spread (...) operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

关于spread(…)操作符https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator的文档说明,请参阅本文

#4


2  

I wanted to find a way to do this with splice() and no iterating: http://jsfiddle.net/jfriend00/W9n27/.

我想找到一种使用splice()而不是迭代的方法:http://jsfiddle.net/jfriend00/W9n27/。

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

a2.unshift(2, 0);          // put first two params to splice onto front of array
a1.splice.apply(a1, a2);   // pass array as arguments parameter to splice
console.log(a1);           // [1, 2, 21, 22, 3, 4, 5];

In general purpose function form:

一般用途:

function arrayInsertAt(destArray, pos, arrayToInsert) {
    var args = [];
    args.push(pos);                           // where to insert
    args.push(0);                             // nothing to remove
    args = args.concat(arrayToInsert);        // add on array to insert
    destArray.splice.apply(destArray, args);  // splice it in
}

#5


1  

If you want to insert another array into an array without creating a new one, the easiest way is to use either push or unshift with apply

如果您想在不创建新数组的情况下向数组中插入另一个数组,最简单的方法是使用push或unshift with apply

Eg:

例如:

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

// Insert a1 at beginning of a2
a2.unshift.apply(a2,a1);
// Insert a1 at end of a2
a2.push.apply(a2,a1);

This works because both push and unshift take a variable number of arguments. A bonus, you can easily choose which end to attach the array from!

这是可行的,因为push和unshift都采用可变数量的参数。一个额外的好处是,您可以轻松地选择从哪个端附加数组!

#6


1  

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

扩展运算符允许在需要多个参数(用于函数调用)或多个元素(用于数组文本)的地方扩展表达式。

a2 = [21,22];
a1 = [1,2,...a2,3,4,5];//...a2 is use of spread operator
console.log(a1);

#7


0  

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

function injectAt(d, a1, a2) {
    for(var i=a1.length-1; i>=d; i--) {
        a1[i + a2.length] = a1[i];
    }
    for(var i=0; i<a2.length; i++) {
        a1[i+d] = a2[i];
    }
}

injectAt(2, a1, a2);

alert(a1);

#8


0  

Here's my version with no special tricks:

以下是我的版本,没有什么特别的技巧:

function insert_array(original_array, new_values, insert_index) {
    for (var i=0; i<new_values.length; i++) {
        original_array.splice((insert_index + i), 0, new_values[i]);
    }
    return original_array;
}

#9


0  

As mentioned in another thread,the answers above will not work in very large arrays (200K elements). See alternate answer here involving splice and manual push: https://*.com/a/41465578/1038326

正如在另一个线程中提到的,上面的答案不能在非常大的数组(200K元素)中工作。请参阅这里涉及到拼接和手动推送的替代答案:https://*.com/a/41465578/1038326

Array.prototype.spliceArray = function(index, insertedArray) {
    var postArray = this.splice(index);
    inPlacePush(this, insertedArray);
    inPlacePush(this, postArray);

    function inPlacePush(targetArray, pushedArray) {
  // Not using forEach for browser compatability
        var pushedArrayLength = pushedArray.length;
        for (var index = 0; index < pushedArrayLength; index++) {
           targetArray.push(pushedArray[index]);
       }
    }
}