我有一個名爲'map.curCellMap'的2d數組存儲1和0。我正在使用函數'cells.getNeighbourCount'(下面)來引用此映射中的單元格。無法讀取由變量造成的未定義屬性
在'cells.update'函數(下面)的上下文中,這返回一個未定義的錯誤。在Firefox中它讀取'TypeError:map.curCellMap [nextY]未定義'。但是,如果我使用硬編碼值調用'cells.getNeighbourCount',它確實有效。
什麼給?
var cells = {
getNeighbourCount: function(x, y) {
/*
/* [y][x]
/* Start a top and move clockwise
*/
var neighbours = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1]],
count = 0;
for(i = 0; i < neighbours.length; i++) {
var curNeighbour = neighbours[i];
//Skip this iteration if neighbour is out of bounds
if((y + curNeighbour[0] < 0) || (y + curNeighbour[0] > ROWS) || (x + curNeighbour[1] < 0) || (x + curNeighbour[1] > COLS)) {
continue;
}
var nextY = y+curNeighbour[0],
nextX = x+curNeighbour[1];
if(map.curCellMap[nextY][nextX] == 1) {
count++;
}
}
return count;
},
update: function() {
for(y = 0; y < ROWS; y++) {
for(x = 0; x < COLS; x++) {
var numNeighbours = this.getNeighbourCount(x, y),
newCellState;
if(numNeighbours >= 2 && numNeighbours <= 3) {
newCellState = 1;
} else {
newCellState = 0;
}
map.nextCellMap[y][x] = newCellState;
}
}
map.curCellMap = map.nextCellMap;
}
}
var map = {
curCellMap: null,
nextCellMap: null,
//Map functions
init: function() {
this.curCellMap = this.generateRandomMap(0.05);
this.nextCellMap = this.curCellMap;
},
generateRandomMap: function(density) {
/*
/* Generates a random cell map
/* density = 0.00 -> No live cells, density = 1.00 -> All cells live
*/
var map = helpers.create2DArray(ROWS, COLS);
for(y = 0; y < ROWS; y++) {
for(x = 0; x < COLS; x++) {
var rand = helpers.getRandomNum(0, 1);
map[y][x] = (rand <= density) ? 1 : 0;
}
}
return map;
}
}
首先,使用var在各自的函數中聲明本地的i,x,y,否則它將成爲全局變量,並且會影響您的其他函數結果。 – Vaibhav 2015-03-02 05:46:46
謝謝,但這並沒有改變任何東西。 – FuriousD 2015-03-02 05:57:18
分享您的完整代碼,我找不到在任何地方定義的ROWS和COLS – Vaibhav 2015-03-02 06:23:42