Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
Function outputs different array but with same input

I'm writing a function for a battleship game that creates a 8x8 grid, and then places two 'ships' at random positions within that grid:

//generates 8x8 board
const generateBoard = () => {
    const gridRow = []
    const gridContainer = []
    for(let i=0; i<8; i++){
      gridRow[i] = ['x']
      gridContainer.push(gridRow)
    }  
    return gridContainer
}


//puts ships at two random positions
const generateBoardWithShips = (board) => { 


  for (let i=0; i<2; i++) { 
    const x = Math.floor(Math.random() * 8);     
    const y = Math.floor(Math.random() * 8);     
    board[y][x] = ['🚢']; 
    coordinates.push(x,y)
   }   
   return board 
  }

//I also have an entire grid saved to variable initialBoardState

const initialBoardState = [
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']]
]

What's confusing me is this: when I pass initialBoardState as an argument to generateBoardWithShips, it works as desired and creates an 8x8 grid with ships at two random positions.
However, when I pass the output of generateBoard (also an 8x8 grid) to generateBoardWIthTwoShips, the output is an grid with two ships in the same position on every row.

I've logged the output of createBoard and it is identical to initialBoardState, so if I'm putting the exact same input into generateBoardWithTwoShips, why is it giving me different outputs?

Summary:

const grid = generateBoard()
generateBoardWithTwoShips(initialBoardState) : works fine
generateBoardWithTwoShips(grid) : prints 2 ships, but in every row
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda