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

前端 未结 2 1069
旧时难觅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);
    };
    

提交回复
热议问题