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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17511273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:35:43  来源:igfitidea点击:

How to replace elements in array with elements of another array

javascript

提问by Artem Svirskyi

I want to replace elements in some array from 0 element, with elements of another array with variable length. Like:

我想将某个数组中的元素从 0 元素替换为另一个长度可变的数组的元素。喜欢:

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

Is there some better way?

有什么更好的方法吗?

回答by Guffa

You can use the splicemethod to replace part of an array with items from another array, but you have to call it in a special way as it expects the items as parameters, not the array.

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

The splicemethod expects parameters like (0, anotherArr.Length, 1, 2, 3), so you need to create an array with the parameters and use the applymethod to call the splicemethod with the parameters:

splice方法需要类似的参数(0, anotherArr.Length, 1, 2, 3),因此需要创建一个带参数的数组,并使用该apply方法调用splice带参数的方法:

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

Example:

例子:

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

Output:

输出:

[ 1, 2, 3, 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Demo: http://jsfiddle.net/Guffa/bB7Ey/

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

回答by caesarsol

In ES6 with a single operation, you can do this to replace the first b.lengthelements of awith elements of b:

在 ES6 中,只需一个操作,您就可以将 的第一个b.length元素替换为的a元素b

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]

It could be also useful to replace the entire content of an array, using a.length(or Infinity) in the splice length:

在拼接长度中使用(或)替换数组的全部内容也可能很有用:a.lengthInfinity

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

a.splice(0, a.length, ...b)
// or
// a.splice(0, Infinity, ...b)

console.log(a) // -> [10, 20, 30], which is the content of b

The aarray's content will be entirely replaced by bcontent.

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

Note: in my opinion the array mutation should only be used in performance-critical applications, such as high FPS animations, to avoid creating new arrays. Normally I would create a new array maintaining immutability.

注意:在我看来,数组突变应该只用于性能关键的应用程序,例如高 FPS 动画,以避免创建新数组。通常我会创建一个保持不变性的新数组。

回答by Kesarion

In ES6, TypeScript, Babel or similar you can just do:

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

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

Simple.

简单的。

回答by Matt Goodwin

For anyone looking for a way to replace the entire contents of one array with entire contents of another array while preserving the original array:

对于任何寻找一种方法来用另一个数组的全部内容替换一个数组的全部内容同时保留原始数组的人:

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

The prototype function takes an array as a parameter which will serve as the new array content, clones it to avoid any weird referential stuff, empties the original array, and then pushes in the passed in array as the content. This preserves the original array and any references.

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

Now you can simply do this:

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

var arr1 = [1, 2, 3];
var arr2 = [3, 4, 5];
arr1.replaceContents(arr2);

I know this is not strictly what the initial question was asking, but this question comes up first when you search in google, and I figured someone else may find this helpful as it was the answer I needed.

我知道严格来说这并不是最初的问题所问的问题,但是当您在 google 中搜索时首先出现这个问题,我想其他人可能会觉得这很有帮助,因为这是我需要的答案。

回答by ZER0

You can just use splice, can add new elements while removing old ones:

您可以只使用splice,可以在删除旧元素的同时添加新元素:

var arr = new Array(10), anotherArr = [1, 2, 3];

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

If you don't want to modify the arrarray, you can use slicethat returns a shallow copy of the array:

如果不想修改arr数组,可以使用返回数组浅拷贝的slice

var arr = new Array(10), anotherArr = [1, 2, 3], result = arr.slice(0);

result.splice.apply(result, [0, anotherArr.length].concat(anotherArr));

Alternatively, you can use sliceto cut off the first elements and adding the anotherArron top:

或者,您可以使用slice切断第一个元素并添加anotherArron top

result = anotherArr.concat(arr.slice(anotherArr.length));

回答by Mattias Buelens

I'm not sure if it's a "better" way, but at least it allows you to choose the starting index (whereas your solution only works starting at index 0). Here's a fiddle.

我不确定这是否是一种“更好”的方式,但至少它允许您选择起始索引(而您的解决方案只能从索引 0 开始)。这是一个小提琴。

// Clone the original array
var result = arr.slice(0);
// If original array is no longer needed, you can do with:
// var result = arr;

// Remove (anotherArr.length) elements starting from index 0
// and insert the elements from anotherArr into it
Array.prototype.splice.apply(result, [0, anotherArr.length].concat(anotherArr));

(Damnit, so many ninjas. :-P)

(该死,这么多忍者。:-P)

回答by 1983

You can just set the length of the array in this case. For more complex cases see @Guffa's answer.

在这种情况下,您可以只设置数组的长度。对于更复杂的情况,请参阅@Guffa 的回答。

var a = [1,2,3];
a.length = 10;
a; // [1, 2, 3, undefined x 7]

回答by Oussama Romdhane

If you want to just copy the values of the first array into the second array just do this

如果您只想将第一个数组的值复制到第二个数组中,请执行以下操作

var secondArray = Object.assign([] ,firstArray);

Here is the Object.assign doc from Mozilla

这是 Mozilla 的 Object.assign 文档