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

174
Visualizações
How to use .indexOf inside a for of loop in js

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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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
});
about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
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