声明一个空的二维阵列在Javascript?阵列、声明、Javascript

2023-09-07 13:50:48 作者:爷丶依旧放肆

我想创建一个二维数组在Javascript中,我要去哪里存储坐标(X,Y)。我还不知道有多少双坐标我会,因为他们会通过用户输入动态地生成。

I want to create a two dimensional array in Javascript where I'm going to store coordinates (x,y). I don't know yet how many pairs of coordinates I will have because they will be dynamically generated by user input.

pre定义二维数组的例子:

Example of pre-defined 2d array:

var Arr=[[1,2],[3,4],[5,6]];

我想我可以使用push方法来添加一个新的记录在数组的末尾。

I guess I can use the PUSH method to add a new record at the end of the array.

我如何声明一个空二维数组,这样,当我用我的第一次Arr.push(),它会被添加到索引0,每一个写的推动下一条记录会在下一次指数?

How do I declare an empty two dimensional array so that when I use my first Arr.push() it will be added to the index 0, and every next record written by push will take the next index?

这可能是很容易做到的,我只是一个JS新手,我会AP preciate如果有人可以写一份简短的工作code片段,我可以检查。谢谢

This is probably very easy to do, I'm just a newbie with JS, and I would appreciate if someone could write a short working code snippet that I could examine. Thanks

推荐答案

您只需声明一个规则排列,像这样:

You can just declare a regular array like so:

var arry = [];

然后,当你有一对值添加到阵列中,所有你需要做的是:

Then when you have a pair of values to add to the array, all you need to do is:

arry.push([value_1, value2]);

是的,你第一次叫 arry.push ,这对价值将被放置在索引0。

And yes, the first time you call arry.push, the pair of values will be placed at index 0.

从nodejs REPL:

From the nodejs repl:

> var arry = [];
undefined
> arry.push([1,2]);
1
> arry
[ [ 1, 2 ] ]
> arry.push([2,3]);
2
> arry
[ [ 1, 2 ], [ 2, 3 ] ]

当然,由于JavaScript的是动态类型,也不会有类型检查执行该阵列保持2维的。你将不得不确保只添加对坐标,而不是执行以下操作:

Of course, since javascript is dynamically typed, there will be no type checker enforcing that the array remains 2 dimensional. You will have to make sure to only add pairs of coordinates and not do the following:

> arry.push(100);
3
> arry
[ [ 1, 2 ],
  [ 2, 3 ],
  100 ]