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

262
Vistas
Iterating String.split() working differently than I expected

I am writing a simple javascript code to parse, and verify a chess position written in Forsyth–Edwards Notation (FEN).

The default chess position in this notation is given by,

const defaultFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";

There are 6 components, I split the components by whitespace using String.split(" "), I now want to further split the first element of the resulting array by "/", which will give the state of each rank.

Running this code gives me an unintuitive result...

const defaultFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
const locations = defaultFEN.split(" ")[0];

for (let rank in locations.split("/")) {
   console.log(rank);
}

I expected the output to be 8 Strings, delimited by "/", in the first portion of the defaultFEN string. Instead I get the numbers 0-7 printing out.

Interestingly, If I manually access this array, console.log(locations.split("/")[i]), for any number i in the interval [0-7], I see the result I intended.

Why are the numbers 0-7 printing out when using the iterative loop, but it works exactly as intended if I use a normal index based for loop?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

There's nothing wrong with your split, but you should use for..of (MDN) instead:

for (let rank of locations.split("/")) {
   console.log(rank);
}

... as for..in loop iterates over indexes (and those are 0..7 for 8-element array).

As a sidenote, it's (usually) a good idea to use const (and not let) in this iteration, as variable is assigned a value once each loop (and usually shouldn't be reassigned):

for (const rank of locations.split("/")) {
   console.log(rank);
}
about 4 years ago · Juan Pablo Isaza Denunciar
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