本文介绍了是什么区别Array.fill和for循环创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React.js创建一个地牢爬虫游戏,我正在使用Array.fill(0)初始化棋盘。但是当我在2d数组中设置一个元素时,它将整个数组(列)设置为'player'而不是单数元素。我有另一个 createBoard()函数,注释掉,它可以正常工作。那么为什么会发生这种情况?如何才能正确使用Array.fill?

I'm creating a dungeon crawler game using React.js and I was initializing the board using Array.fill(0). but when I set an element inside the 2d array it sets the entire Array (column) to 'player' instead of a singular element. I have another createBoard() function, commented out, that works correctly. So why does this happen and how can I use Array.fill correctly?

这是我的Board组件:

Here is my Board component:

import React, {Component} from 'react';
import Cell from './Cell';

class Board extends Component {
  constructor(props) {
    super(props);
    const dim = 10;
    let board = this.createBoard(dim, dim);
    this.state = {
      board: board,
    };
  }

  createBoard = (row, col) => {
    return Array(row).fill(Array(col).fill(0));
  }

  // createBoard = (rows, cols) => {
  //   let board = [];
  //   for (let i = 0; i < rows; i++) {
  //     let row = [];
  //     for (let j = 0; j < cols; j++) {
  //       row.push(0);
  //     }
  //     board.push(row);
  //   }
  //   console.log(board);
  //   return board;
  // }

  movePlayer = () => {

  }

  componentDidMount() {
    this.setPiece(this.props.player);
  }

  setPiece = (loc) => {
    let brd = this.state.board;
    const row = loc[0];
    const col = loc[1];
    console.log('row: '+row+' col: '+col+' ==='+brd[row][col]);
    brd[row][col] = 'player';
    console.log('setPiece: ',brd);
    this.setState({board: brd});
  }

  renderCell = (cell) => {
    switch(cell) {
      case 0:
        return 'floor';
      case 1:
        return 'wall';
      case 'player':
        return 'player';
      default:
        return 'floor';
    }
  }

  render() {
    return (
      <div className='board'>
      {this.state.board.map((row, i) => {
        return row.map((cell, j) => {
          return (
            <Cell
              key={[i, j]}
              loc={[i, j]}
              type={this.renderCell(cell)}
            />
          );
        })
      })}
      </div>
    );
  }
}

export default Board;


推荐答案

您可以借助Array填充2D数组。填写这样的方式:

You can fill 2D array with a help of Array.fill in a such way:

let arr = Array(5).fill(0).map(x => Array(5).fill(0))

这篇关于是什么区别Array.fill和for循环创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:50