为什么这个二维数组出现错误? [英] Why am I getting an error with this 2d array?

查看:57
本文介绍了为什么这个二维数组出现错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var arr = [[],[]];
var si = 5;
var c  = 0;
if (arr[si][c] == null)
{
     arr[si][c] = {
           code : "Test",
     };
}
alert(arr[si][c].code);

您好,我正在尝试运行此示例代码,但出现错误,说无法调用未定义的属性0".

Hello, I am trying to run this sample code but I am getting an error, saying that the attribute "0" of an undefined can not be called.

尴尬的是,如果我使用数值代替变量si"和c"作为索引,错误就不会出现!

The awkward thing is that if I use numeric values instead of the variables "si" and "c" for the index, the error doesn't show up!

有没有可能在 JS 中不能使用变量作为索引?我认为它确实适用于非二维数组.

Is it possible that in JS you can not use variables as an Index? I think it does work with a non two dimensional array.

谢谢并致以最诚挚的问候

Thank you and best regards

推荐答案

JavaScript 没有任何二维数组的概念.只是包含其他数组的数组.

JavaScript doesn't have any concept of 2 dimensional arrays. Just arrays that contain other arrays.

arr[si][c]arr[5][0].

arr 是一个包含两个成员(01)的数组,每个成员都是一个数组.

arr is an array with two members (0 and 1), each of which is an array.

当您访问 arr[5] 时,您会得到 undefined,因为您已经超出了终点.

When you access arr[5] you get undefined because you have gone beyond the end.

undefined[0] 是一个错误.

尴尬的是,如果我使用数值代替变量si"和c"作为索引,错误就不会出现!

The awkward thing is that if I use numeric values instead of the variables "si" and "c" for the index, the error doesn't show up!

如果你使用文字而不是变量,你会得到同样的错误.大概你的工作测试涉及不同的数字.

You get the same error if you use literals instead of variables. Presumably your working test involved different numbers.

var arr = [[],[]];
if (arr[5][0] == null)
{
     arr[5][0] = {
           code : "Test",
     };
}
alert(arr[5][0].code);

这篇关于为什么这个二维数组出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆