Home > Software engineering >  error cannot read properties of undefined (reading 'indexOf')
error cannot read properties of undefined (reading 'indexOf')

Time:06-09

I have an array named : board_3x3_squars It has 9 rows with numbers 1 to 9 in each row.

I want to create a new array with the values of the index of a random value (1 to 9) in each of the rows in array board_3x3_squars. so for example if value 5 is in index 2 of row 0 in board_3x3_squars I want the new array for value 5 to be like: new array = [2]

the for loop is giving me the following error: "Cannot read properties of undefined (reading 'indexOf')"

and I don't know how to solve it. Code:

for (let i = 0; i <= board_3x3_squars.length; i  ) {
  let valIndex = [];
  let val = [];
  val = board_3x3_squars[i].indexOf(randmNum());
  valIndex.push(val);
}

This is the randNum function :

let numPick;
const chosenNumPick = [];

function randmNum() {
  let min = Math.ceil(1);
  let max = Math.floor(9);
  numPick = Math.floor(Math.random(1, 9) * (max - min   1)   min);
  if (chosenNumPick.includes(numPick)) {
    randmNum();
  } else if (chosenNumPick.lenth < 9) {
    chosenNumPick.push(numPick);      }
  return numPick;
}

CodePudding user response:

board_3x3_squars[i] returns a number (a value in the array at index i). You are then calling the indexof method on this number (val = board_3x3_squars[i].indexOf(randmNum());), which is not correct. You can only call indexof on an array (e.g. board_3x3_squars.indexof(randmNum()))

CodePudding user response:

Your code is working fine. I just created a working code snippet. Can you please have a look and let me know what challenges you are facing.

let numPick;
const chosenNumPick = [];
const board_3x3_squars = [[1 , 2, 3, 4, 5, 6, 7, 8, 9]];

function randmNum() {
  let min = Math.ceil(1);
  let max = Math.floor(9);
  numPick = Math.floor(Math.random(1, 9) * (max - min   1)   min);
  if (chosenNumPick.includes(numPick)) {
    randmNum();
  } else if (chosenNumPick.lenth < 9) {
    chosenNumPick.push(numPick);      }
  return numPick;
}
  
let valIndex = [];

for (let i = 0; i < board_3x3_squars.length; i  ) {
  let val = [];
  const randumNum = randmNum();
  val = board_3x3_squars[i].indexOf(randumNum);
  valIndex.push({
    val: randumNum,
    index: val
  });
}

console.log(valIndex);

  • Related