console.log(r[a][b]);
if(r[a-1][b-1] != '-' && r[a-1][b-1] != '+' && r[a-1][b-1] != '*' && r[a-1][b-1] != '#')
r[a-1][b-1] -= Q;
When I tried to execute it with the relevant content
TypeError: Cannot read property '3' of undefined
This error occurs.
console.log(r[a][b]);
console.log(r[a-1][b-1]);
+After taking a log like this, the first line runs and the second line has the same error
Why does this error occur?
javascript
I think you answered in the comments, so I'm going to explain a little bit.
var a = [1, 2, 3];
JavaScript does not fail when referring to places outside the range of the array. Returns undefined
instead. Therefore, a[3]
returns undefined
.
a[3]
// // => undefined
However, if the referenced array is a double array,
var b = [ [1, 2, 3], [4, 5, 6] ];
If you think about it in order of operation, b[2][2]
can be replaced with (b[2])[2]
, that is, the structure returns an array from the first index operator and references it again.
b[2]
is undefined
, so if you change the expression above, (b[2])[2]
becomes (undefined)[2]
. undefined
is trying to find the second index, but undefined
is not an array.
Therefore, an error such as TypeError: Cannot read property '3' of undefined
occurs. In one-dimensional array indexing, undefined
came out, where I tried to find the third index.
The reason for Cannot read property
is that JavaScript searches for member indexes are the same operation as finding members of an object. That is,
a[2]
and a.2"
are the same. Of course, it's not grammatically correct, so the second one is grammatically incorrect. By definition, the index of the array is also treated as a member of the object.
Therefore, you can also query objects upside down like an array.
var obj = {
1 : "mem1",
"2": "mem2",
"prop" : "mem3"
}
You can also access obj["1"]
, obj[2]
, and obj["prop"]
.
© 2024 OneMinuteCode. All rights reserved.