【发布时间】:2016-12-04 22:51:28
【问题描述】:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<style>
td
{
min-height: 50px;
min-width: 50px;
}
</style>
</head>
<body>
<table border="1" id="tab">
<tr>
<td class="game"></td>
<td class="game"></td>
<td class="game"></td>
<td class="game"></td>
</tr>
<tr>
<td class="game"></td>
<td class="game"></td>
<td class="game"></td>
<td class="game"></td>
</tr>
<tr>
<td class="game"></td>
<td class="game"></td>
<td class="game"></td>
<td class="game"></td>
</tr>
<tr>
<td class="game"></td>
<td class="game"></td>
<td class="game"></td>
<td class="game"></td>
</tr>
</table>
<script>
var tab=[4];
$(document).ready(function()
{
var i,j;
for(i=0;i<4;i++)
{
tab[i]=[4];
for(j=0;j<4;j++)
{
tab[i][j]=null;
}
}
randomnum();
});
function randomnum()
{
var num=Math.random();
alert("called random num");
if(num<0.5)
num=2;
else
num=4;
alert(num);
var row=Math.floor(Math.random()*10);
row=row%4;
var col=Math.floor(Math.random()*10);
col=col%4;
while(tab[row][col]!=null)
{
var row=Math.random();
row=(row*10)%4;
var col=math.random();
col=(col*10)%4;
alert("random row col"+row+" "+col);
}
//alert("row:"+row+"col"+col);
tab[row][col]=num;
$("#tab tr:eq("+row+") td:eq("+col+")").text(num);
keycheck();
}
function keycheck()
{
$(document).on("keydown",function(event){
if(event.which==38)
moveup();
else if(event.which==40)
movedown();
else if(event.which==39)
moveright();
else if(event.which==37)
moveleft();
});
}
function moveup()
{
var row,col,j;
for(col=0;col<4;col++)
{
for(row=0;row<3;row++)
{
if(tab[row][col]==tab[row+1][col])
{
tab[row][col]=tab[row][col]*2;
row++;
tab[row][col]=null;
}
}
for(row=0;row<3;row++)
{
for(j=row+1;j<4;j++)
{
if (typeof j === "undefined") {
alert("j is undefined");
}
if (typeof row === "undefined") {
alert("col is undefined");
}
if (typeof col === "undefined") {
alert("col is undefined");
}
alert(j+" "+row+" "+col);
if(tab[j][col]==null&&tab[j+1][col]!=null)
{
tab[j][col]=tab[j+1][col];
tab[j+1][col]=null;
j++;
}
}
}
}
chntable();
}
function chntable()
{
var row,col;
for(row=0;row<4;row++)
{
for(col=0;col<4;col++)
{
$("#tab tr:eq("+row+") td:eq("+col+")").text(num);
}
}
randomnum();
}
</script>
</body>
</html>
在上面的代码中我得到了
Cannot read property '0' of undefined
moveup() 在if(tab[j+1][col]==null&&tab[j][col]!=null)。错误是什么以及如何解决?从警报消息中,我可以看到没有一个是未定义的。那么是什么引发了问题呢?问题的原因是什么,所以我将来可以避免它?重复给出的是创建一个数组,尽管它没有解决我的问题。 jquery 库中的错误在dispatch 和q.handle。
【问题讨论】:
-
tab只有一个键index(0),它的值是4... -
@Rayon 为什么在任何其他选项卡调用中都没有抛出错误以及如何解决它
-
@Rayon 还有其他方法可以在 jquery 中创建静态 4X4 数组
-
为什么将数组与
jQuery关联起来?创建一个矩阵很简单。我无法理解你想用你的代码实现什么...... -
@Rayon 我正在尝试创建 [2048 游戏]2048game.com。所以我想要一个 4X4 数组来存储值。
标签: javascript jquery html-table