Javascript 在reactjs中创建网格
我需要解释一下在这个构造函数的gridFull状态下做了什么。由于对javascript不熟悉,我无法获得这行代码Javascript 在reactjs中创建网格,javascript,reactjs,Javascript,Reactjs,我需要解释一下在这个构造函数的gridFull状态下做了什么。由于对javascript不熟悉,我无法获得这行代码 constructor() { super(); this.speed = 100; this.rows = 30; this.cols = 50; this.state = { generation: 0, gridFull: Array(this.r
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
}
让我们把这句话分解一下:
Array(this.rows)
这将创建一个包含this.rows
多行的数组。在这种情况下,30
.fill()
用未定义的值()
这将返回一个新数组,其中每个值都由函数转换。由于您有一个未定义的数组
,因此将像调用以下callbackFunction(未定义)
一样调用该函数
现在是回调函数:
() => Array(this.cols).fill(false);
此函数不接受任何参数(因此()
),并返回一个带有This.cols
大小(50)的数组,所有数组都包含false
tl;博士:
因此,您实际上是在每个元素上创建一个30x50矩阵,填充false
编辑:
说明箭头功能:
(list-of-parameters) => (function block | return value)
为了使用示例进行解释,我们可以将函数one(){return 1;}
转换为()=>1代码>
或函数时间(a,b){返回a*b;}
到(a,b)=>a*b代码>
或其他:
let x = 0;
function foo(y) {
const returnValue = (x++) * y;
return returnValue;
}
到
编辑2:
实现相同结果的更多方法:
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 = [];
for (let idx = 0; idx < rowCount; idx++) {
result.push([...line]);
}
你从哪里得到这个密码的?上下文是什么/它应该做什么?你不理解代码的哪一部分?您是否尝试过用谷歌搜索各种方法,例如.fill()
和.map()
单独使用?我了解.fill和.map在javascript中的作用,因此得到了这段代码,但我对它们如何与箭头函数一起使用感到非常困惑。@satyajeetjha注意到答案是如何将您所询问的代码行分割成小块的。每一篇文章的描述都可以通过一些研究找到,通常从谷歌开始。在您继续学习编程的过程中,将事物分解成更小的部分是一项关键技能。祝你好运这很有帮助。你能再举几个例子来说明这个概念吗?我已经添加了更多的例子。我不知道你是不是在找这个。让我知道。
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]);
}
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);
},
};
}