簡體   English   中英

錯誤無法讀取未定義的屬性(讀取“indexOf”)

[英]error cannot read properties of undefined (reading 'indexOf')

我有一個名為: board_3x3_squars的數組,它有 9 行,每行的數字為 1 到 9。

我想用數組 board_3x3_squars 中每一行的隨機值(1 到 9)的索引值創建一個新數組。 因此,例如,如果值 5 在 board_3x3_squars 中第 0 行的索引 2 中,我希望值 5 的新數組如下所示:new array = [2]

for 循環給我以下錯誤:“無法讀取未定義的屬性(讀取‘indexOf’)”

而且我不知道如何解決。 代碼:

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

這是 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;
}

board_3x3_squars[i]返回一個數字(數組中索引i處的值)。 然后您在這個數字上調用indexof方法( val = board_3x3_squars[i].indexOf(randmNum()); ),這是不正確的。 您只能在數組上調用indexof (例如board_3x3_squars.indexof(randmNum())

您的代碼工作正常。 我剛剛創建了一個工作代碼片段。 您能否看一下,讓我知道您面臨的挑戰是什么?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM