Why can't I make a copy of this 2d array in JS? How can I make a copy?

柔情痞子 提交于 2019-12-01 12:18:45

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())

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().

You may clone an ND (deeply nested) array as follows;

Array.prototype.clone = function(){
  return this.map(e => Array.isArray(e) ? e.clone() : e);
};

or if you don't want to modify Array.prototype you may simply refactor the above code like;

function cloneArray(a){
  return a.map(e => Array.isArray(e) ? cloneArray(e) : e);
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!