Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda