I'm a beginner to JavaScript working on my first project: Tic Tac Toe!
I'm trying to write a function that will use a for/of loop to look through all the spaces on the game board and return an array of numbers corresponding with the index of any space that has an X in it.
spaceArray is the game board, with random x's in it for now.
Here is my attempt at the function:
var s = '_'
var x = 'X'
var O = 'O'
var spaceArr = [s, s, s, x, s, s, s, s, x]
function spaceChecker(array) {
let currGame = []
for (var element of array) {
if (element === 'X')
currGame.push(array.indexOf(element))
}
return currGame
}
console.log(spaceChecker(spaceArr))
It currently returns:
[ 3, 3 ]
How can I get .indexOf to update each time the for/of loops?
You have used indexOf which will return the first index of the X every time you are searching for X. If you want to use for..of loop then you have to track the index at which you are on.
var s = "_";
var x = "X";
var O = "O";
var spaceArr = [s, s, s, x, s, s, s, s, x];
function spaceChecker(array) {
let currGame = [];
let index = 0;
for (var element of array) {
if (element === "X") {
currGame.push(index);
}
index++;
}
return currGame;
}
console.log(spaceChecker(spaceArr));
ALTERNATE SOLUTION ⬇
You can just use reduce here to get the index of the X in an array
var s = "_";
var x = "X";
var O = "O";
var spaceArr = [s, s, s, x, s, s, s, s, x];
function spaceChecker(array) {
return array.reduce((acc, curr, index) => {
if (curr === "X") acc.push(index);
return acc;
}, []);
}
console.log(spaceChecker(spaceArr));
As you do not need to return anything from the loop you can use forEach loop.
forEach((element, index) => {
// if condition met push index in custom array
});
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
So your code will always return 3 because that will be the first index where X is found on every iteration.
It's much easier to use a basic for/loop and push the index of the current iteration into currGame when X is found.
const s = '_';
const x = 'X';
const O = 'O';
const spaceArr = [s, s, s, x, s, s, s, s, x];
function spaceChecker(array) {
const currGame = [];
for (let i = 0; i < array.length; i++) {
if (array[i] === 'X') currGame.push(i);
}
return currGame;
}
console.log(spaceChecker(spaceArr));