javascript数组未定义问题
下面代码运行提示78行的的0没有定义请问下是什么情况
Uncaught TypeError: Cannot read property '0' of undefined
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>贪吃蛇</title>
<script type="text/javascript">
//MAP绘制
function Map() {
var w = 800
var h = 400
this.showmap = function () {
//创建样式
var mb = document.createElement('div')
mb.style.width = w + "px"
mb.style.height = h + "px"
mb.style.backgroundColor = "black"
mb.style.backgroundImage = "url(1.jpg)"
document.body.appendChild(mb)
}
}
//绘制食物
function Food() {
var bc = 20;//边长
this.showfood = function () {
//用DOM创建一个DIV.绘制一个CSS的颜色背景作为食物
//宽度到高度一样均20
//最后把DIV追加到BODY里
//SW=食物.bc=边长
var sw = document.createElement('div')
sw.style.width = sw.style.height = bc + "px";
sw.style.backgroundColor = "red"
//绝对定位
sw.style.position = "absolute"
document.body.appendChild(sw)
//边长20的话走一步20距离地图大小800*400.去除边框也就是(800-20)*(400-20)X=0-39步Y=0-19步
var x = Math.floor(Math.random() * 40)
var y = Math.floor(Math.random() * 20)
sw.style.left = x * bc + "px"//边长*总的随机步数值
sw.style.top = y * bc + "px";
}
}
//绘制蛇
function Snake() {
var bc = 20 //边长
this.snakebody = [[0,1,'green'],[1,1,'green'],[2,1,'green'],[3, 1, '#670808']];
//蛇头移动的方向默认右边
this.redirect = "right"
//绘制蛇
this.showsnake = function () {
for (var i = 0; i < this.snakebody.length; i++) {
var sj = document.createElement('div')//sj=蛇节
sj.style.height = sj.style.width = bc + "px"
sj.style.backgroundColor = this.snakebody[i][2];//this.snakebody[i][2]
//绝对定位
sj.style.position = "absolute"
//设置坐标=蛇的坐标*步进值
//第一条蛇节
sj.style.left = this.snakebody[i][0] * bc + "px"
sj.style.top = this.snakebody[i][1] * bc + "px"
document.body.appendChild(sj)
}
}
//移动方法
this.movesnake = function () {
for (var i = 0; i < this.snakebody.length; i++) {
this.snakebody[i][0] = this.snakebody[i - 1][0];
this.snakebody[i][1] = this.snakebody[i - 1][1];
}
//蛇头移动
// if(this.redirect == 'right')
//
// this.snakebody[length-1][0]++;
// //x++
// else if (this.redirect == 'left')
// this.snakebody[length-1][0]--;
// //x--
// else if (this.redirect == 'top')
// this.snakebody[length-1][0]--;
// //y--
// else if (this.redirect == 'top')
// this.snakebody[length-1][0]++;
// //y++
}
}
window.onload = function () {
//加载地图
var map = new Map()
map.showmap()
//加载食物
var food = new Food()
food.showfood()
//加载蛇
snake = new Snake()
snake.showsnake()
//移动
setInterval("snake.movesnake()", 1000)
// snake.movesnake()
}
</script>
<style type="text/css">
body {
margin: 0
}
</style>
</head>
<body>
</body>
</html>