Javascript 我想用另一个数组值替换所有值,两个数组的大小相同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30640771/
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-08-23 05:30:36  来源:igfitidea点击:

I want to replace all values with another array values , both arrays are in same size

javascript

提问by SUGU

eg:

例如:

var Array1=array(1,2,3,4,5,6);
var Array2=array(7,8,9,10,11,12);

after replacing Array2with Array1values Resulting array should be

Array2Array1值替换后结果数组应该是

var Array1=array(7,8,9,10,11,12);

回答by broofa

Prior ES6 (using push):

之前的 ES6(使用push):

Array1.length = 0;                  // Clear contents
Array1.push.apply(Array1, Array2);  // Append new contents



Post ES6 (using splice):

发布 ES6(使用splice):

Array1.splice(0, Array1.length, ...Array2);

回答by Andy

Use slice:

使用slice

Array1 = Array2.slice(0);

This will take a copyof Array2, notmake a referenceto it, so if you make changes to Array2they won't be reflected in Array1.

这将需要复制Array2不是做一个参考吧,所以如果你修改了Array2他们不会被反射Array1

DEMO

演示

回答by Dary

With for loop:

使用 for 循环:

var Array1=[1,2,3,4,5,6];
var Array2=[7,8,9,10,11,12];
for (var i = 0; i < Array1.length; i++){
  Array1[i] = Array2[i]
}
console.log(Array1)

回答by Bruno Araujo

in this example, it is possible to exclude the value of an array of type CONST, and the value of an array is passed to or another. I had this problem.

在这个例子中,可以排除类型为 CONST 的数组的值,并将数组的值传递给或另一个。我有这个问题。

fields = [1,2,3,4]

var t = fields.filter(n => {
  return n != 4;
});

// t => [1,2,3]

fields.splice(0, fields.length, ...t);

console.log(fields);//[1,2,3]