JavaScript - why Array.prototype.fill actually fills a “pointer” of object when filling anything like 'new Object()'

后端 未结 4 801
囚心锁ツ
囚心锁ツ 2020-11-27 21:56

I was trying to used Array.prototype.fill method to create a n x n 2D array but the code was buggy and I eventually found out all arrays inside are actually

4条回答
  •  暖寄归人
    2020-11-27 22:46

    In your particular case, since Array.prototype.fill() fills with a single value and in JS objects (such as arrays) are reference types you have all indices carry a reference to the first one. In JS creating an ND array may not be as simple as it seems since arrays will be copied by reference. For a general purpose arrayND function you need an array cloning utility function. Let's see;

    Array.prototype.clone = function(){
      return this.map(e => Array.isArray(e) ? e.clone() : e);
    };
    function arrayND(...n){
      return n.reduceRight((p,c) => c = (new Array(c)).fill().map(e => Array.isArray(p) ? p.clone() : p ));
    }
    var array3D = arrayND(5,5,5,"five");
    array3D[0][1][2] = 5;
    console.log(array3D);

    arrayND function takes indefinite number of arguments. The last one designates the default value to fill our ND array and the preceding arguments are the sizes of each dimension they represent. (first argument is dimension 1, second argument is dimension 2 etc...)

提交回复
热议问题