[英]2D array returning wrong value
var term = [,];
term[0,0]="0";
term[0,1]="1";
term[1,0]="2";
term[1,1]="3";
alert(term[0,1]);
Returns 3, and I don't know why. 返回3,我不知道为什么。 Logically, it should return 1, correct?
从逻辑上讲,它应该返回1,对吗?
In JavaScript, when you have an expression like a, b
, it will evaluate both a
and b
and the result of the expression will be b
. 在JavaScript中,当您拥有类似
a, b
的表达式时,它将同时评估a
和b
并且表达式的结果将为b
。 You can confirm that like this 您可以像这样确认
console.log((1, 2));
# 2
console.log((0, 1));
# 1
console.log((1, 0));
# 0
So, 所以,
term[0, 0] = "0";
term[0, 1] = "1";
term[1, 0] = "2";
term[1, 1] = "3";
was evaluated like this 像这样被评估
term[0, 0] = term[0] = "0";
term[0, 1] = term[1] = "1";
term[1, 0] = term[0] = "2";
term[1, 1] = term[1] = "3";
So the actual array has got only 2
and 3
. 因此,实际数组只有
2
和3
。 Now, you are trying to access, 0, 1
, which is equivalent to 现在,您正在尝试访问
0, 1
,它等效于
term[0, 1] = term[1]
That is why you are getting 3
. 这就是为什么你得到
3
。
To actually create a 2-D Array, you create a main array and keep adding subarrays to it, like this 要实际创建二维数组,您需要创建一个主数组,并不断向其添加子数组,如下所示
var term = [];
term.push([0, 1]);
term.push([2, 3]);
Now, to access value at 0, 1
, you need to do like this 现在,要访问
0, 1
值,您需要这样做
term[0][1]
By 2D it's meant [[]]
, not [,]
jsBin example 2D表示
[[]]
,不是[,]
jsBin示例
var term = [[],[]];
term[0][0]="0";
term[0][2]="1";
term[1][0]="2";
term[1][3]="3";
console.log( term ); // [["0", "1"], ["2", "3"]]
console.log( term[0][1] ); // "1"
Also you can insert/append keys into an array using Array.prototype.push() 您也可以使用Array.prototype.push()将键插入/追加到数组中
JavaScript arrays don't work that way. JavaScript数组不能那样工作。
Here is an example that should work: 这是一个应该起作用的示例:
var term = []; // Create array
term[0] = ["0", "1"]; // What you referred to as [0,0] and [0,1]
term[1] = ["2", "3"]; // What you referred to as [1,0] and [1,1]
alert(term[0][1]); // Proper JavaScript way to access 2D array.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.