在reactjs

时间:2018-01-24 19:50:44

标签: javascript reactjs

我需要一个解释,就像在这个构造函数的gridFull状态中所做的那样。作为javascript的新手,我无法得到这行代码。

constructor() {
        super();
        this.speed = 100;
        this.rows = 30;
        this.cols = 50;

        this.state = {
            generation: 0,
            gridFull: Array(this.rows).fill().map(() => Array(this.cols).fill(false))// this line of code is unclear to me
        }

1 个答案:

答案 0 :(得分:1)

让我们打破界限:

Array(this.rows)

这将创建一个this.rows行的数组。在这种情况下,30。

.fill()

使用undefined值(more info on fill function

填充数组
.map(callbackFunction)

返回一个新数组,每个值都由函数转换。由于您有一个undefined数组,因此您可以像调用以下callbackFunction(undefined)一样调用该函数。

现在回调函数:

() => Array(this.cols).fill(false);

此函数不带参数(因此()),并返回一个this.cols大小(即50)的数组,都包含false。

TL; DR: 因此,您实际上是在每个元素上创建一个填充false的30x50矩阵。

编辑:

解释箭头功能:

(list-of-parameters) => (function block | return value)

为了解释使用示例,我们可以将function one() { return 1; }转换为() => 1;

function times(a, b) { return a * b;}进入(a, b) => a * b;

或另一个:

let x = 0;
function foo(y) {
  const returnValue = (x++) * y;
  return returnValue;
}

let x = 0;
const foo = (y) => {
  const returnValue = (x++) * y;
  return returnValue;
}

EDIT2:

实现相同结果的更多方法:

let result = Array(rowCount).fill();
for (let i = 0; I < rowCount; i++) {
  result[i] = Array(colCount).fill(false);
}

另:

const line = Array(colCount).fill(false);
const result = Array(rowCount).fill().map(() => [...line]);

另一个:

const line = Array(colCount).fill(false);
const result = [];
for (let idx = 0; idx < rowCount; idx++) {
  result.push([...line]);
}

或者您可以创建自己的&#34;矩阵创建者&#34;:

function matrix(row, col) {
  const data = Array(row * col).fill(false);

  const findIdx = (x, y) => y * col + x;

  return {
    get: (x, y) => data[findIdx(x,y)],
    set: (x, y, value) => {
      data[findIdx(x,y)] = value
      return data[findIdx(x,y);
    },
  };
}
相关问题