Iterating String.split() working differently than I expected

63 Views Asked by At

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?

1

There are 1 best solutions below

1
raina77ow On

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);
}