Javascript 如何创建点数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3593934/
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
How do I create an array of Points?
提问by coure2011
How to create point object containing x,y and creating its array? so that i can loop over those points, add/remove points dynamically.
如何创建包含 x,y 的点对象并创建其数组?这样我就可以遍历这些点,动态添加/删除点。
回答by karim79
var points = [{x:45, y:64}, {x:56, y:98}, {x:23, y:44}];
var len = points.length;
for(var i = 0; i < len; i++) {
alert(points[i].x + ' ' + points[i].y);
}
?
// to add more points, push an object to the array:
points.push({x:56, y:87});
回答by Guffa
You can create a constructor for a Point object like this:
您可以为 Point 对象创建一个构造函数,如下所示:
function Point(x, y) {
this.x = x;
this.y = y;
}
Now you can create Point objects using the newkeyword:
现在您可以使用new关键字创建 Point 对象:
var p = new Point(4.5, 19.0);
To create an array of Point objects you simply create an array, and put Point objects in it:
要创建 Point 对象数组,您只需创建一个数组,并将 Point 对象放入其中:
var a = [ new Point(1,2), new Point(5,6), new Point(-1,14) ];
Or:
或者:
var a = [];
a.push(new Point(1,2));
a.push(new Point(5,6));
a.push(new Point(-1,14));
You use the .operator to access the properties in the Point object. Example:
您可以使用.运算符访问 Point 对象中的属性。例子:
alert(a[2].x);
Or:
或者:
var p = a[2];
alert(p.x + ',' + p.y);
回答by Felix Kling
I suggest you read about JavaScript arraysto learn all that. It is important that you know the basics.
我建议您阅读JavaScript 数组以了解所有内容。了解基础知识很重要。
Example for adding:
添加示例:
var points = [];
points.push({x:5, y:3});
回答by Geuis
Faster, more efficient:
更快、更高效:
var points = [ [45,64], [56,98], [23,44] ];
for(var i=0, len=points.length; i<len; i++){
//put your code here
console.log( 'x'+points[i][0], 'y'+points[i][1] )
}
// to add more points, push an array to the array:
points.push([100,100]);
The efficiency will only really be noticeable in a very large array of points.
只有在非常大的点数组中,效率才会真正引人注目。

