javascript摆脱数组引用

时间:2017-08-31 11:11:23

标签: javascript arrays reactjs reference

这是一个反应扫雷,当用户想要选择新的网格大小时,它涉及setState。当用户点击网格时应重新创建,但由于prev状态,存在一些参考问题。

当我第一次console.log(array);时,由于普通状态,它不是空的。当我console.log(array[m][n]['value'])时它表示所有值都是0,但是当我console.log(array);之后,数组包含'b'值,这些值是从addBombs方法设置的createMap

我该怎么办?

createMap (sizeX, sizeY, bombNumber) {
  let array = [];
  while (array.length > 0) {
    array.pop();
  }
  array.length = 0;
  console.log(array); // not totally empty, but it says length 0.

  for (var m = 0; m < sizeY; m++) {
    array[m] = new Array();
    for (var n = 0; n < sizeX; n++) {
      array[m][n] = { value: 0, state: 'closed' };
      console.log(array[m][n]['value']); // Prints 0 for all of them.
    }
  }
  console.log(array); // There are 'b' values in the array.
  return array.slice();
}

createTable(props) {
  const sizeX = props.sizeX;
  const sizeY = props.sizeY;
  const bombNumber = props.bombNumber;

  const map = this.createMap(sizeX, sizeY, bombNumber);
  const newMap = map.slice();
  const newestMap = this.addBombs(newMap, sizeX, sizeY, bombNumber);
  const newestestMap = newestMap.slice();
  const mMap = this.calculateFieldValues(newestestMap);
  const nMap = mMap.slice();
  return nMap;
}

addBombs (map, sizeX, sizeY, bombNumber) {
  let bombFields = [];

  while (bombFields.length < bombNumber) {
    const randomNumber = Math.floor(Math.random() * (sizeY * sizeX - 1))
    if (!bombFields.includes(randomNumber)) {
      bombFields.push(randomNumber);
    }
  }

  bombFields.forEach((number) => {
    const i = Math.floor(number / sizeX);
    let j = (number % sizeX);
    if (j === -1) {
      j = sizeX - 1;
    }
    map[i][j]['value'] = 'b';
  });

  return map;
}

enter image description here

0 个答案:

没有答案