本文介绍了为什么我不能在JS中复制这个2d数组?我怎样才能复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实施John Conway生命游戏,但我遇到了一个奇怪的问题。如果代码给我带来麻烦,这是一个简短版本:

I'm implementing a John Conway Game of Life, but I'm having a weird problem. Here is a short version if the code giving me trouble:

let lifeMap = [
  [true, false, false],
  [false, false, false],
  [false, false, false]
];
let oldLifeMap = lifeMap.slice();
for (let row = 0; row < lifeMap.length; row++) {
  for (let val = 0; val < lifeMap[row].length; val++) {
    let bool = lifeMap[row][val];
    let newBool = false; // here is where I would determine if cell is alive/dead
    lifeMap[row][val] = newBool;
    if (row === 0 && val === 0) console.log("at (0,0)", oldLifeMap[0][0]);
  }
}

为了响应此代码,JavaScript打印 at(0,0)false 。我需要它保持 true 直到下一代开始。

In response to this code, JavaScript prints at (0,0) false. I need it to stay true until the next generation starts.

我想做让oldLifeMap = lifeMap.slice()会解决它,但事实并非如此,我不知道为什么。 (不应该复制 2d数组并且不创建第二个引用吗?)

I thought doing let oldLifeMap = lifeMap.slice() would fix it, but it doesn't, and I'm not sure why. (Shouldn't it copy the 2d array and not create a second ref to it?)

无论如何,这里发生了什么,以及如何在此成功制作 lifeMap 的实际副本?

Anyway, what is going on here, and how do I successfully make an actual copy of lifeMap here?

推荐答案

的标题提示,这对于N维数组很有用,但特别是对于2D数组,没必要。为了深入克隆你的特定2D数组,你需要做的就是:

A hat-tip to @Redu's answer which is good for N-dimensional arrays, but in the case of 2D arrays specifically, is unnecessary. In order to deeply clone your particular 2D array, all you need to do is:

let oldLifeMap = lifeMap.map(inner => inner.slice())

这将使用<$ c创建每个内部数组的副本$ c> .slice()没有参数,并将其存储到使用 .map()创建的外部数组的副本。

This will create a copy of each inner array using .slice() with no arguments, and store it to a copy of the outer array made using .map().

这篇关于为什么我不能在JS中复制这个2d数组?我怎样才能复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 04:18