im using for to assign a value to an array but when I print the array it just shoes the last value in the full array

后端 未结 2 2035
-上瘾入骨i
-上瘾入骨i 2021-01-21 23:12

I created an array using the array class with size of 8 * 8 and filling it with a dumy object using fill . and after that I created a for and assigning the values . but when I p

2条回答
  •  面向向阳花
    2021-01-21 23:42

    If you look at the description of Array.prototype.fill() method on MDN, it says:

    If the first parameter is an object, each slot in the array will reference that object

    So unlike you expected, there is only one object in memory and each slot in the array is referencing that same object.

    Following code snippet demonstrates this behavior

    let arr = Array(3).fill({});
    arr[0].a = "hello";
    
    arr.forEach(obj => console.log(obj));

    Solution:

    There is no need to initially fill the array with objects, you could just create a new object each time addElement() function, add key-value pairs in the newly created object and add this object in the array.

    var gridSize = 8;
    const colorname = ['Red', 'Orange', 'Green', 'Blue', 'Purple', 'Yellow'];
    
    var gameGrid = new Array(gridSize * gridSize).fill(null);
    fillTheGrid();
    
    function fillTheGrid() {
      for (var i = 0; i < gridSize * gridSize; i++) {
        addElement(i);
      }
    }
    
    function addElement(i) {
      const obj = {};
      obj.loc = i;
      let randomColor = Math.floor(Math.random() * colorname.length);
      obj.color = colorname[randomColor];
      obj.index = i;
      obj.value = i;
      
      gameGrid[i] = obj;
    }
    
    console.log(gameGrid);

提交回复
热议问题