[英]Keep Getting "TypeError: Cannot set property '1' of undefined"
I'm trying to solve algorithm problems, but I keep getting this error, and it frustrate me:我正在尝试解决算法问题,但我不断收到此错误,这让我很沮丧:
var data = [".......", "...O...", "....O..", ".......", "OO.....", "OO....."]
var R = 6;
var C = 7;
var N = 3;
var cell = new Array(R);
for (i=0; i<R; i++) {
cell[i] = new Array(C);
}
for (i=0; i<R; i++) {
var currentRow = data[i].split("");
for (j=0; j<C; j++) {
cell[i][j] = currentRow[j];
}
}
for (x=0; x<=N; x++) {
for (i=0; i<R; i++) {
for (j=0; j<C; j++) {
if (cell[i][j] == '.') {
cell[i][j] = 0;
} else if (cell[i][j] == 'O') {
cell[i][j] = 1;
} else if (cell[i][j] == 3) {
cell[i][j] = 0;
// Why are these following 4 LINES are not working???
cell[i + 1][j] = 0;
cell[i - 1][j] = 0;
cell[i][j + 1] = 0;
cell[i][j - 1] = 0;
} else if (cell[i][j] >= 0) {
cell[i][j] += 1;
}
}
}
}
The culprit is when we are trying to use 2D array with some operation like罪魁祸首是当我们尝试使用二维数组进行某些操作时
cell[i + 1][j] = 0;
cell[i - 1][j] = 0;
cell[i][j + 1] = 0;
cell[i][j - 1] = 0;
I dont know why but keep getting TypeError: Cannot set property '1' of undefined
我不知道为什么,但一直收到
TypeError: Cannot set property '1' of undefined
If the first horizontal or first vertical cell of your array is equal 3, than you can't do i - 1
or j -1
.如果数组的第一个水平或第一个垂直单元格等于 3,则不能执行
i - 1
或j -1
。 Same thing if the last horizontal cell or the last vertical cell equals 3, you can't do i + 1
or j + 1
.如果最后一个水平单元格或最后一个垂直单元格等于 3,则不能执行
i + 1
或j + 1
。 So you just have to check wheter is not the first or the last vertical cell of your bidimensional array.因此,您只需要检查是否不是二维数组的第一个或最后一个垂直单元格。
It looks like these lines of code are sometimes accessing out of bounds on your arrays.看起来这些代码行有时会超出数组的访问范围。 The code will work without the error message by changing those 4 lines to guarantee the access remains in bounds, like this:
通过更改这 4 行代码以确保访问保持在边界内,代码将在没有错误消息的情况下工作,如下所示:
// Why are these following 4 LINES are not working???
if (i < R - 1) {
cell[i + 1][j] = 0;
}
if (i > 0) {
cell[i - 1][j] = 0;
}
if (j < C - 1) {
cell[i][j + 1] = 0;
}
if (j > 0) {
cell[i][j - 1] = 0;
}
Here's a link to a jsfiddle where I have placed the updated code.这是我放置更新代码的 jsfiddle的链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.