[英]How can I create a 2d array in react.js from a json object?
I have this code:我有这个代码:
fetch(' https://localhost:9000/maze')
.then(res => res.json())
.then((data) => {
this.setState({maze: data })
})
.catch(console.log);
Which should give me (for example):这应该给我(例如):
[["WALL","WALL","WALL","WALL","WALL"],["WALL","OPEN","OPEN","OPEN","WALL"],["WALL","OPEN","WALL","WALL","WALL"],["WALL","OPEN","OPEN","OPEN","WALL"],["WALL","WALL","WALL","WALL","WALL"]]
I want the 2d array as variable in which I will loop further down the code.我希望二维数组作为变量,我将在其中进一步循环代码。 And want to draw the maze onto a canvas like this:
并想像这样将迷宫绘制到 canvas 上:
for (var y = 0; y < size; y++) {
var field = test[y];
for (var x = 0; x < size; x++) {
if (field[x] === 'WALL') {
console.log("[" + x + "][" + y + "] " + field[y]);
ctx.drawImage(wall, (width / size) * x, (height / size) * y, width / size, height / size);
}
}
}
This blocks works with a hardcoded 2d array so the only thing I need is a 2d array from the json.这个块适用于硬编码的二维数组,所以我唯一需要的是来自 json 的二维数组。
Do you want to parse JSON?是否要解析 JSON? If so then use
如果是这样,那么使用
const parsedJson = JSON.parse(jsonStringToBeParsed)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.