JavaScript 中的奇怪数组行为
Odd array behaviour in JavaScript
我正在尝试使用 JavaScript 在 canvas 上绘制方框;我的代码有效,但我的数组有问题。假设我有一个名为 map
的多维数组,它的声明如下:
var map = [
[0,1,1],
[0,0,1],
[0,1,1],
];
其中 1
是一个框,0
是空白 space,但是当我 运行 我的代码输出如下所示:
0,0,0
1,0,1
1,1,1
有什么方法可以解决这个问题,使输出匹配 map
?我的代码如下所示:
var canvas = null;
var ctx = null;
var x,y,count,inc,ax,ay;
var map = [
[0,0,0],
[1,0,1],
[1,1,1],
];
window.onload = function () {
canvas = document.getElementById("gameArea");
ctx = canvas.getContext("2d");
y=0;
x=0;
ax=0;
ay=0;
count=0;
inc=0;
for(;count<3;count++){
if(count>0){
inc = inc + 40;
console.log("inc:"+inc);
console.log();
}
ay=count;
console.log("ay:"+ay);
console.log();
y = y + inc;
console.log("y:"+y);
console.log();
for(;ax<3;x=x+40,ax++){
if(map[ax][ay]==1){
console.log(ax+","+ay)
console.log(map[ax][ay]);
console.log();
ctx.strokeRect(x,y,40,40);
console.log("block:"+x+","+y);
}
}
console.log();
x=0;
y=0;
ax=0;
}
};
而HTML如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Single Stage</title>
<script src="js/game.js" type="text/javascript">
</script>
<style type="text/css">
#gameArea{
display:block;
margin:0 auto;
background-color:#FFFFFF;
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameArea" width='800' height='480'></canvas>
</body>
</html>
您刚刚混淆了行和列
尝试将 map[ax][ay]==1
切换为 map[ay][ax]==1
我正在尝试使用 JavaScript 在 canvas 上绘制方框;我的代码有效,但我的数组有问题。假设我有一个名为 map
的多维数组,它的声明如下:
var map = [
[0,1,1],
[0,0,1],
[0,1,1],
];
其中 1
是一个框,0
是空白 space,但是当我 运行 我的代码输出如下所示:
0,0,0
1,0,1
1,1,1
有什么方法可以解决这个问题,使输出匹配 map
?我的代码如下所示:
var canvas = null;
var ctx = null;
var x,y,count,inc,ax,ay;
var map = [
[0,0,0],
[1,0,1],
[1,1,1],
];
window.onload = function () {
canvas = document.getElementById("gameArea");
ctx = canvas.getContext("2d");
y=0;
x=0;
ax=0;
ay=0;
count=0;
inc=0;
for(;count<3;count++){
if(count>0){
inc = inc + 40;
console.log("inc:"+inc);
console.log();
}
ay=count;
console.log("ay:"+ay);
console.log();
y = y + inc;
console.log("y:"+y);
console.log();
for(;ax<3;x=x+40,ax++){
if(map[ax][ay]==1){
console.log(ax+","+ay)
console.log(map[ax][ay]);
console.log();
ctx.strokeRect(x,y,40,40);
console.log("block:"+x+","+y);
}
}
console.log();
x=0;
y=0;
ax=0;
}
};
而HTML如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Single Stage</title>
<script src="js/game.js" type="text/javascript">
</script>
<style type="text/css">
#gameArea{
display:block;
margin:0 auto;
background-color:#FFFFFF;
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameArea" width='800' height='480'></canvas>
</body>
</html>
您刚刚混淆了行和列
尝试将 map[ax][ay]==1
切换为 map[ay][ax]==1