gpt4 book ai didi

javascript - 在 React 中使用 2D map 打印棋盘

转载 作者:行者123 更新时间:2023-12-04 14:47:48 25 4
gpt4 key购买 nike

我对 react 还很陌生,但我没有使用常见的 js for 循环,而是想弄清楚如何使用 .map() 来获得相同的结果。

 import React from 'react'
import './styles/Board.css'
import Tile from './Tile'

const Board = () => {
let board = []
printBoard(board)
return (
<div className="board">
{ board }
</div>
)
}

const printBoard = (board) => {

const boardY = [1, 2, 3, 4, 5, 6, 7, 8]
const boardX = ['a','b','c','d','e','f','g','h']

for(let x = 0; x < boardX.length; x++) {
for(let y = boardY.length - 1; y >= 0; --y) {
//saves the position in each square ex: b1
const pos = boardX[x] + "" + boardY[y]
//paints the squares and the positions
board.push(<Tile key={pos} color={ (x + y) % 2 === 0 ? "dark" : "light" } pos={pos} />)
}
}
}
export default Board

Current render

enter image description here

最佳答案

在使用 map 函数执行相同操作时,您需要切换循环(外部和内部)。并且 y 必须替换为 (boardY.length - (yIndex + 1)) 以获得递减索引。

试试下面

const Board = () => {
return <div className="board">{printBoard()}</div>;
};

const printBoard = () => {
const boardY = [1, 2, 3, 4, 5, 6, 7, 8];
const boardX = ["a", "b", "c", "d", "e", "f", "g", "h"];
const boardYRevered = boardY.reverse();

return boardYRevered.flatMap((y, yIndex) => {
return boardX.map((x, xIndex) => {
const pos = `${x}${y}`;
return (
<Tile
key={pos}
color={
(xIndex + (boardY.length - (yIndex + 1))) % 2 === 0
? "dark"
: "light"
}
pos={pos}
/>
);
});
});
};

注意:如果您想要棋盘的二维数组,请将flatMap 更改为map

关于javascript - 在 React 中使用 2D map 打印棋盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69689418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com