[英]Concise way to copy array elements in JavaScript
I need to copy elements from one JavaScript array to another. 我需要将元素从一个JavaScript数组复制到另一个。 Yes, I know there are oodles of questions regarding cloning an array, but most of the related answers create a new copy of the existing array.
是的,我知道克隆数组存在很多问题,但是大多数相关的答案都会创建一个现有数组的新副本。 I already have a copy of an array I want to keep.
我已经有一个要保留的数组的副本。 I merely want to update the values with those of another array.
我只想用另一个数组的值更新值。 Like this:
像这样:
//I already have this array
const oldArray = new Array(10);
//here is a new array I get from somewhere
const newArray = new Array(10).fill(3);
//I just want to copy the values, not create a new array
for(let i = 0; i < newArray.length; i++) {
oldArray[i] = newArray[i];
}
Is there some cool, slick way to do that, perhaps using ES6 syntax? 是否有一些很酷,巧妙的方法可以执行此操作,也许使用ES6语法?
You can use Array#splice to remove from the start an amount of items in the oldArray
equals to the newArray
length, and then add to it all items in the newArray
: 您可以使用Array#splice从一开始就删除
oldArray
等于newArray
长度的项目,然后将newArray
所有项目添加到其中:
const oldArray = new Array(10).fill(4); const newArray = new Array(5).fill(3); oldArray.splice(0, newArray.length, ...newArray); console.log(oldArray);
You can use Object.assign()
您可以使用
Object.assign()
const arr = [1,2,3]; const values = [4,5,6]; Object.assign(arr, ...values.map((prop, index) => ({[index]:prop}))); console.log(arr);
You could just use Object.assign
with an array as target and an array as source. 您可以只使用
Object.assign
并将数组作为目标,并将数组作为源。
All values of own enumerable keys of the array, are transfered to the target array with the same index. 数组自己的可枚举键的所有值都将以相同的索引传输到目标数组。
var oldArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], newArray = [10, 11, 12, 13, 14]; Object.assign(oldArray, newArray); console.log(oldArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.