【问题标题】:Change Array[3] for every item in other array为其他数组中的每个项目更改 Array[3]
【发布时间】:2020-10-22 04:14:15
【问题描述】:

编辑 在我的问题中犯了一个错误。 let tempArr = splitArr 是错误的。这需要是: tempArr = 汽车。所以@Prime 和@sabbir.alam 的遮阳篷可以解决问题!


我有一个值数组,其中一个值(car[3])是一个由“,”分隔的字符串。我用 .split(", ") 创建了这些元素的新数组 (splitArr)。

现在我想创建 n 个数组并将 car[3] 替换为 splitArr 中的一个项目。但我的结果只有 splitArr 的最后一个值。

我尝试了 .map .forEach for 循环。 .arryafunction 或 for 循环内部和外部的 tempArr。但总是相同的结果,而 splitArr.forEach 中的 console.log 显示了 splitArr 的每一项。下面是一些视觉指导。

代码

const car = [ 
  'BMW',
  'Serie1',
  'Gray',
  'Wheels, Lights, Alarm' ]

const splitArr = car[3].split(", ");
const newArr = [];

splitArr.forEach(item => {
  console.log(item);
  let tempArr = splitArr; // This needs to be: car!
  tempArr[3] = item;
  newArr.push(tempArr);
});

console.log(newArr);

结果

Wheels
Lights
Alarm
[
  [ 'Wheels', 'Lights', 'Alarm', 'Alarm' ],
  [ 'Wheels', 'Lights', 'Alarm', 'Alarm' ],
  [ 'Wheels', 'Lights', 'Alarm', 'Alarm' ]
]

想要的结果

Wheels
Lights
Alarm
[
  [ 'BMW', 'Serie1', 'Gray', 'Wheels' ],
  [ 'BMW', 'Serie1', 'Gray', 'Lights' ],
  [ 'BMW', 'Serie1', 'Gray', 'Alarm' ]
]

提前致谢!

【问题讨论】:

  • 请将想要的结果添加为数据结构。
  • @NinaScholz 你的意思是想要的结果?

标签: javascript node.js arrays


【解决方案1】:

您的代码不起作用的主要原因是您不了解在 JavaScript 中克隆数组的正确方法。您可以在此处获取更多详细信息。 https://www.samanthaming.com/tidbits/35-es6-way-to-clone-an-array/

const car = [ 
    'BMW',
    'Serie1',
    'Gray',
    'Wheels, Lights, Alarm' ]
  
  const splitArr = car[3].split(", ");
  const newArr = [];
  
  splitArr.forEach(item => {
    console.log(item);
    let tempArr = [...splitArr]; // <----------------------------------
    tempArr[3] = item;
    newArr.push(tempArr);
  });
  
  console.log(newArr);

【讨论】:

    【解决方案2】:

    这是因为您不断添加相同的数组 (splitArr) 并对其进行修改。您需要每次都进行深层复制:

      ...
      let tempArr = JSON.parse(JSON.stringify(splitArr));
      tempArr.push(item);
      ...
    

    请注意,使用push 更安全,因为如果您犯了上述错误,您会注意到,因为数组将继续增长而不是更改。

    【讨论】:

      【解决方案3】:

      使用map() 将是一个不错的策略。对于每次迭代,返回与新数组中的当前项一起循环的数组。

      const car = [ 
        'BMW',
        'Serie1',
        'Gray',
        'Wheels, Lights, Alarm' 
      ];
      
      const splitArr = car[3].split(", ");
      const result = splitArr.map((item, i, arr) => [...arr, item]);
      
      console.log(result);

      【讨论】:

        【解决方案4】:

        您应该像这样let tempArr = [...splitArr] 创建临时数组。当您直接分配 splitArray 时,您引用的是同一个数组。所以任何对 tempArray 的更新都会反映在 splitArray 上。

        【讨论】:

          猜你喜欢
          • 2016-06-23
          • 2011-04-21
          • 1970-01-01
          • 2022-08-24
          • 2020-07-12
          • 1970-01-01
          • 2011-06-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多