在 Javascript 中声明一个空的二维数组? [英] Declare an empty two-dimensional array in Javascript?

查看:26
本文介绍了在 Javascript 中声明一个空的二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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.

预定义二维数组示例:

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,并且 push 写入的每个下一条记录都将采用下一个索引?

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 新手,如果有人可以编写一个我可以检查的简短工作代码片段,我将不胜感激.谢谢

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 是动态类型的,因此不会有强制数组保持二维的类型检查器.您必须确保只添加坐标对,而不是执行以下操作:

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 ]

这篇关于在 Javascript 中声明一个空的二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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