为什么这段 JavaScript 代码不起作用?
var arrayi = new Array();
for (var i=0; i<=9; i++)
{
for (var o=0; o<=9; o++)
{
arrayi[i][o]=i + "" + o;
}
}
for (var i = 0, j = 9; i <= 9; i++, j--)
document.write("arrayi[" + i + "][" + j + "]= " + arrayi[i][j]);
我试图将 00 分配给 arrayi[0][0],将 62 分配给 arrayi[6][2] 等,然后显示 [0][9],[1][8]...
var arrayi = new Array();
for (var i=0; i<=9; i++)
{
for (var o=0; o<=9; o++)
{
arrayi[i][o]=i + "" + o;
}
}
for (var i = 0, j = 9; i <= 9; i++, j--)
document.write("arrayi[" + i + "][" + j + "]= " + arrayi[i][j]);
I'm trying to assign 00 to arrayi[0][0], 62 to arrayi[6][2] etc.. and then display [0][9], [1][8]...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
JavaScript 中的数组是一维的。
所以
arrayi[0]
是undefined
,那么arrayi[0][0]
就变成undefined[0]
,显然不起作用。您需要通过将数组分配给 arrayi 的索引来创建一个二维数组,所分配的实际值也存在错误:
关于自动分号插入搞砸了,请看一下:
所以JS正在修复你的代码......错误的方式:)
更新
我有点不清楚你到底想做什么,如果你想将一个数字分割成小数位然后分配比你首先必须确保你的数组足够大,然后你必须分割数字:
Arrays in JavaScript are one dimensional.
So
arrayi[0]
isundefined
, thenarrayi[0][0]
becomesundefined[0]
which obviously doesn't work.You need to create a two dimensional array by assigning arrays to the indexes of
arrayi
, there's also an error with the actual value that's being assigned:Concerning automatic semicolon insertion screwing you up, take a look at this:
So JS is fixing your code... the wrong way :)
Update
It's a bit unclear to me what you exactly want to do, if you want to split a number into it's to decimal places and then assign that, than you will first have to make sure that your arrays are big enough and then you have to split the number:
我猜你的目标是这样的:
I'm guessing you're aiming at something like this:
第六行有
i + o
,其中 i 和 o 是数字,它们将作为数字添加。0 + 0 = 0
和6 + 2 = 8
。要连接字符串,您需要将数字转换为字符串。最简单的方法是添加一个空字符串;数组i[i][o] = i + "" + o
Your sixth line has
i + o
, where i and o are Numbers, which will be added as numbers.0 + 0 = 0
, and6 + 2 = 8
. To concatenate strings you need to convert the numbers to strings. The simplest way to do that is to add an empty string;arrayi[i][o] = i + "" + o
改变这个,
用;
Change this,
with;
尝试
或者
Try either
or
要以数字方式分配它,您需要:
To assign this numerically, you'd need this:
当您运行该代码时,您会收到错误
ReferenceError:arrayi未定义
。您需要先设置 arrayi[i],然后再将另一个项目分配给它,就好像它是一个数组一样。我建议尽可能使用
push
来设置数组元素。这段代码怎么样:
输出:
这就是你想要的,对吧?
一份额外小费;我建议在 JavaScript 中使用
var array=[]
而不是new Array()
。When you run that code, you get the error
ReferenceError: arrayi is not defined
.You need to set arrayi[i] before assigning another item to it as if it's an array. I suggest using
push
when possible to set array elements.How about this code:
Output:
That's what you wanted, right?
One extra tip; I suggest
var array=[]
rather thannew Array()
in JavaScript.document.write("arrayi[" + i + "][" + j + "]= " + a[i][j]);
你调用 a 而不是 arrayi
document.write("arrayi[" + i + "][" + j + "]= " + a[i][j]);
You call a instead of arrayi