Javascript javascript创建多维数组语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4962086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript creating multi-dimensional array syntax
提问by Dan
Today I've heard that it's possible to create a multi - dimensional array in js using this syntax:
今天我听说可以使用以下语法在 js 中创建一个多维数组:
var a = new Array(3,3);
a[2][2] = 2;
alert(a[2][2])
However this doesn't work in opera. Am I wrong somewhere?
然而,这在歌剧中不起作用。我有什么地方错了吗?
回答by Quentin
Yes, you are wrong somewhere. var a = new Array(3,3);
means the same as var a = [3,3];
. It creates an array with two members: the Number 3
and the Number 3
again.
是的,你哪里错了。var a = new Array(3,3);
与 的意思相同var a = [3,3];
。它创建了一个包含两个成员的数组:Number3
和 Number 3
。
The array constructor is one of the worst parts of the JavaScript language design. Given a single value, it determines the length of the array. Given multiple values, it uses them to initialise the array.
数组构造函数是 JavaScript 语言设计中最糟糕的部分之一。给定一个值,它确定数组的长度。给定多个值,它使用它们来初始化数组。
Always use the var a = [];
syntax. It is consistent (as well as being shorter and easier to read).
始终使用var a = [];
语法。它是一致的(以及更短且更易于阅读)。
There is no short-cut syntax for creating an array of arrays. You have to construct each one separately.
没有用于创建数组数组的快捷语法。您必须分别构建每一个。
var a = [
[1,2,3],
[4,5,6],
[7,8,9]
];
回答by Chris Baker
The code you posted makes an array consisting of two integers. You're then trying to treat an integer as an array.
您发布的代码制作了一个由两个整数组成的数组。然后,您尝试将整数视为数组。
mv = new Array();
mv[0] = new Array();
mv[0][0] = "value1-1";
mv[0][1] = "value1-2";
mv[1] = new Array();
mv[1][0] = "value2-1";
mv[1][1] = "value2-2";
There is no way to directly instantiate a multidimensional array.
没有办法直接实例化一个多维数组。
回答by gion_13
you want to create an array of arrays, but you're creating an array with 2 elements:
您想创建一个数组数组,但您正在创建一个包含 2 个元素的数组:
var a = new Array(3,3);
// a = [3,3]
if you want to create a multidimensional array, you have to think in terms of array of arrays.
this way, a 2 dimensional array (or matrix) would be defined as :
如果你想创建一个多维数组,你必须考虑数组的数组。
这样,一个二维数组(或矩阵)将被定义为:
var a = [[],[]];//or var a = new Array([],[]);
//or if you want to initialize the matrix :
var b = [
[1,2],
[3,4]
];