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

前端 未结 2 1067
旧时难觅i
旧时难觅i 2020-12-06 23:10

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         


        
相关标签:
2条回答
  • 2020-12-06 23:29

    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);
    };
    
    0 讨论(0)
  • 2020-12-06 23:33

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

    0 讨论(0)
提交回复
热议问题