简体   繁体   中英

Javascript Typerror variable undefined.

I m trying to make a simple dumb tic-tac-toe game using HTML, CSS and Javascript.

In the below function for the player move the ComputerMove Function cannot be called because of Typeerror in JSON object.

function Mymove(idValue) 
{
 var flag=0;
 var image = document.getElementById(idValue);
 if (image.src.match("blank.png")) {
 image.src = "X.png";
 flag=Check();
 if (flag==1) 
  {
  alert("You Won");
  reset();
  return;
  };
 ComputerMove();
 };
} 
function Check(){
   for (var i =0 ; i <= 8;i++) {
   var image=document.getElementById(winList[i].a);
   if (!image.src.match("blank.png")) {
   if(image.src==document.getElementById(winList[i].b).src && image.src==document.getElementById(winList[i].c).src)
   return 1;
 }
 }

Here is the JSON object below:-

var winList =[
    {a:1,b:2,c:3},
    {a:4,b:5,c:6},
    {a:7,b:8,c:9},
    {a:1,b:4,c:7},
    {a:2,b:5,c:8},
    {a:3,b:6,c:9},
    {a:1,b:5,c:9},
    {a:3,b:5,c:7}];

The check function works always, and the console response as

TypeError: winList[i] is undefined

While Debugging I found after this error the ComputerMove() function never gets called. So please help.

Your winList array has a length of 8, with an index spanning from 0 - 7.

Your loop for (var i =0 ; i <= 8;i++) tries to access the winList[8] (when the i == 8 ), which is undefined - thus crashing the script when you try to access a of undefined ( winList[i].a ).

Try changing your loop condition to the following: for (var i = 0 ; i < 8; i++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM