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

后端 未结 4 796
囚心锁ツ
囚心锁ツ 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:39

    With recursion you can make even more dimensions ;)

    const range = r => Array(r).fill().map((v, i) => i);
    const range2d = (x, y) => range(x).map(i => range(y));
    const rangeMatrix = (...ranges) => (function ranger(ranged) {
      return ranges.length ? ranger(range(ranges.pop()).map(i => ranged)) : ranged
    })(range(ranges.pop()));
    
    let arr10x10 = range2d(10, 10);
    let arr3x5 = range2d(3, 2);
    let arr4x3 = rangeMatrix(4, 3);
    let arr4x3x2 = rangeMatrix(4, 3, 2);
    let arr4x3x2x5 = rangeMatrix(4, 3, 2, 5);
    
    console.log(arr10x10);
    console.log(arr3x5);
    console.log(arr4x3);
    console.log(arr4x3x2);
    console.log(arr4x3x2x5);

提交回复
热议问题