将数据按顺序插入数组
我目前正在尝试弄清楚如何设计某种循环来将数据顺序插入到数组中。我在 Unity3D 引擎中使用 Javascript。
基本上,我想在数组中存储一堆坐标位置。每当用户单击屏幕时,我的脚本都会获取坐标位置。问题是,我不确定如何将其插入数组中。
我如何检查数组的索引以确保是否采用 array[0],然后使用 array[1]?也许某种 For 循环或计数器?
谢谢
I am currently trying to figure out how to design some sort of loop to insert data into an array sequentially. I'm using Javascript in the Unity3D engine.
Basically, I want to store a bunch of coordinate locations in an array. Whenever the user clicks the screen, my script will grab the coordinate location. The problem is, I'm unsure about how to insert this into an array.
How would I check the array's index to make sure if array[0] is taken, then use array[1]? Maybe some sort of For loop or counter?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要添加到数组末尾,只需使用 .push()。
myArray,现在包含两个项目(每个项目都是两个坐标的数组)。
现在,如果您只是像我在这里所做的那样静态声明所有内容(您可以静态声明整个数组),您就不会这样做,但我只是制作了这个示例来向您展示推送如何添加一个将项目放到数组的末尾。
请参阅 https://developer.mozilla.org/en/JavaScript/Reference/ Global_Objects/Array/push 有关推送的一些参考文档。
如果以后读取数组时需要知道数组的长度,可以使用 .length 属性。
To just add onto the end of an array, just use .push().
myArray, now contains two items (each which is an array of two coordinates).
Now, you wouldn't do it this way if you were just statically declaring everything as I've done here (you could just statically declare the whole array), but I just whipped up this sample to show you how push works to add an item onto the end of an array.
See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push for some reference doc on push.
In case you need to know the array's length when reading the array in the future, you can use the .length attribute.
我也建议使用 jfriend00 建议的
.push()
方法,但是要回答您有关如何计算下一个索引是什么的问题,您可以使用数组的length
财产。因为 JavaScript 数组是从零开始的,所以length
属性将返回一个比当前最高索引高 1 的整数,因此如果您想要,length
也将是要使用的索引值在末尾添加另一个项目:anArray[anArray.length] = someValue; // 添加到数组末尾
要获取数组中的最后一个元素,您当然可以说
anArray[anArray.length-1]
。请注意,在大多数情况下,
length
将给出数组中的元素数量,但我在上面说“比当前最高索引高一个”,因为 JavaScript 数组非常乐意让您跳过索引:Using the
.push()
method as suggested by jfriend00 is my recommendation too, but to answer your question about how to work out what the next index is you can use the array'slength
property. Because JavaScript arrays are zero-based Thelength
property will return an integer one higher than the current highest index, solength
will also be the index value to use if you want to add another item at the end:anArray[anArray.length] = someValue; // add to end of array
To get the last element in the array you of course say
anArray[anArray.length-1]
.Note that for most purposes
length
will give the number of elements in the array, but I said "one higher than the current highest index" above because JavaScript arrays are quite happy for you to skip indexes: