为什么我不能在 JS 中复制这个二维数组?如何制作副本? [英] Why can't I make a copy of this 2d array in JS? How can I make a copy?

查看:32
本文介绍了为什么我不能在 JS 中复制这个二维数组?如何制作副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实施 John Conway Game of Life,但我遇到了一个奇怪的问题.如果代码给我带来麻烦,这里是一个简短的版本:

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.

我认为做 let oldLifeMap = lifeMap.slice() 会解决它,但它没有,我不知道为什么.(难道不应该复制二维数组而不是创建第二个引用吗?)

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?

推荐答案

@Redu's answer 的提示对 N 维数组很有用,但特别是在 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())

这将使用不带参数的 .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 中复制这个二维数组?如何制作副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆