用其他数组中的元素替换Javascript数组元素

时间:2018-11-26 00:15:30

标签: javascript multidimensional-array

我有以下简单的代码,可以使用Java Array

  var fruits = [["Banana", "Orange", "Apple", "Mango"]];
  var names  =  ["Adam", "Emma", "Joe", "David"];                
  var newArray=[];

  for (var i = 0 ; i < 4 ; i++){      
    newArray[i] = fruits[0];    // Copy fruits[] into newArray[] 
    newArray[i][1] = names[i];  // Then replace the 2nd element with names[]    
  } 

渴望的结果就是这个...

newArray[0] = ["Banana", "Adam" , "Apple", "Mango"]
newArray[1] = ["Banana", "Emma" , "Apple", "Mango"]
newArray[2] = ["Banana", "Joe"  , "Apple", "Mango"]
newArray[3] = ["Banana", "David", "Apple", "Mango"]

但是我得到了最终结果,无法弄清楚为什么...

newArray[0] = ["Banana", "David" , "Apple", "Mango"]
newArray[1] = ["Banana", "David" , "Apple", "Mango"]
newArray[2] = ["Banana", "David" , "Apple", "Mango"]
newArray[3] = ["Banana", "David" , "Apple", "Mango"]

我对JS只是一个新手,所以认为这可能归结为简单的事情,但在阶段这是无法通过的砖墙。您的帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

问题是:

newArray[i] = fruits[0];    // Copy fruits[] into newArray[] 

newArray[i]不是fruits中第一个项目的副本-而是对内存中同一对象的另一个引用。因此,当您更改newArray[i]时,您还更改了fruits[0],并且还更改了其他所有对fruits[0]都具有相同引用的变量-即,每个 newArray中的项目。

改为在每次迭代中克隆fruits[0]

var fruits = [
  ["Banana", "Orange", "Apple", "Mango"]
];
var names = ["Adam", "Emma", "Joe", "David"];
var newArray = [];

for (var i = 0; i < 4; i++) {
  newArray[i] = [...fruits[0]];
  newArray[i][1] = names[i];
}
console.log(newArray);

[...fruits[0]]是扩展语法-它创建fruits[0]的浅表副本。

尽管您可能会考虑使用.map来代替,但是当您从另一个元素的每个元素创建新数组时,.map更为合适:

var fruits = [
  ["Banana", "Orange", "Apple", "Mango"]
];
var names = ["Adam", "Emma", "Joe", "David"];

const newArray = names.map((name) => {
  const arr = [...fruits[0]];
  arr[1] = name;
  return arr;
});
console.log(newArray);

或者,不扩散,使用slice

var fruits = [
  ["Banana", "Orange", "Apple", "Mango"]
];
var names = ["Adam", "Emma", "Joe", "David"];

const newArray = names.map((name) => {
  const arr = fruits[0].slice();
  arr[1] = name;
  return arr;
});
console.log(newArray);