如何用另一个数组的元素替换数组中的元素

Art*_*kyi 31 javascript

我想从0元素替换某些数组中的元素,另一个数组的元素具有可变长度.喜欢:

var arr = new Array(10), anotherArr = [1, 2, 3], result;
result = anotherArr.concat(arr);
result.splice(10, anotherArr.length);
Run Code Online (Sandbox Code Playgroud)

有更好的方法吗?

Guf*_*ffa 48

您可以使用该splice方法将数组的一部分替换为另一个数组中的项,但您必须以特殊方式调用它,因为它期望项作为参数,而不是数组.

splice方法需要参数(0, anotherArr.Length, 1, 2, 3),因此您需要使用参数创建一个数组,并使用applysplice方法使用以下参数调用该方法:

Array.prototype.splice.apply(arr, [0, anotherArr.length].concat(anotherArr));
Run Code Online (Sandbox Code Playgroud)

例:

var arr = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var anotherArr = [ 1, 2, 3 ];

Array.prototype.splice.apply(arr, [0, anotherArr.length].concat(anotherArr));

console.log(arr);
Run Code Online (Sandbox Code Playgroud)

输出:

[ 1, 2, 3, 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/Guffa/bB7Ey/

  • 如果第一个数组长于替换数,则上述解决方案不会删除末尾的额外元素.稍作修改将:Array.prototype.splice.apply(arr,[0,arr.length] .concat(anotherArr)); (3认同)

cae*_*sol 28

在具有单个操作的ES6中,您可以执行此操作来替换阵列的整个内容:

let a = [1,  2,  3,  4,  5]
let b = [10, 20, 30]

a.splice(0, b.length, ...b)

console.log(a) // -> [10, 20, 30, 4, 5]
Run Code Online (Sandbox Code Playgroud)

b.length阵列的内容将被完全替代a的内容.

请注意,这应仅用于性能关键型应用程序,例如高FPS动画,以避免创建新阵列.

通常我会创建一个新的数组来维护不变性.

编辑:我刚刚意识到这并没有完全回答这个问题,但它可以帮助一些谷歌.

  • 只需使用`a.splice(0,Infinity,... b)`.第二个参数是无关紧要的,只要它大于要删除的元素数. (3认同)
  • 很好,但最初的问题是如何替换第一个数组的一部分。它应该是`a.splice(0, b.length, ...b)` - 而是测量 b 的长度。它将与两个数组的任何长度一起正常工作 (2认同)

Mat*_*win 5

对于任何想要在保留原始数组的同时用另一个数组的全部内容替换一个数组的整个内容的方法:

Array.prototype.replaceContents = function (array2) {
    //make a clone of the 2nd array to avoid any referential weirdness
    var newContent = array2.slice(0);
    //empty the array
    this.length = 0;
    //push in the 2nd array
    this.push.apply(this, newContent);
};
Run Code Online (Sandbox Code Playgroud)

原型函数将数组作为参数,将其作为新的数组内容,克隆它以避免任何奇怪的引用内容,清空原始数组,然后将传入的数组作为内容推送.这会保留原始数组和任何引用.

现在你可以简单地这样做:

var arr1 = [1, 2, 3];
var arr2 = [3, 4, 5];
arr1.replaceContents(arr2);
Run Code Online (Sandbox Code Playgroud)

我知道这不是最初问题的严格要求,但是当你在谷歌搜索时,这个问题首先出现,我认为其他人可能会觉得这很有用,因为这是我需要的答案.


Kes*_*ion 5

在ES6,TypeScript,Babel或类似的中你可以这样做:

arr1.length = 0; // Clear your array
arr1.push(...arr2); // Push the second array using the spread opperator
Run Code Online (Sandbox Code Playgroud)

简单.