如何在javascript中将值分配给多维数组? [英] how to assign values to multidimensional arrays in javascript?
本文介绍了如何在javascript中将值分配给多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试通过以下方式做到这一点:
I tried to do this with:
arr[i][j] = 'whatever';
但是我遇到某种错误无法转换为对象..."
but I get some kind of error "cannot convert to object..."
推荐答案
当您尝试将其视为数组时,我想您还没有初始化a[i]
.如果您在说a[i][j]
时没有将a[i]
初始化为数组,那么它将是未定义的(或者其他不是数组或对象的东西),并且不知道[j]
是什么意思,因此,您的无法转换为对象"错误.您需要更多类似这样的东西:
I'm going to guess that you haven't initialized a[i]
when you try to treat it like an array. If you haven't initialized a[i]
to be an array when you say a[i][j]
, then it will be undefined (or something else that isn't an array or object) and that doesn't know what [j]
means, hence your "cannot convert to an object" error. You need something more like this:
var a = [ ];
for(var i = 0; i < 10; ++i) {
a[i] = [ ];
for(var j = 0; j < 10; ++j) {
a[i][j] = 42; // a[i] is now an array so this works.
}
}
这篇关于如何在javascript中将值分配给多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文