我想创建一些对象,如object_point1,object_point2,... 使用for循环,用x和y coords分割字符串。 我如何使用iterates来创建对象的名称? 感谢
var vMsg = req.body.myMessage;
var fields = vMsg.split(/\n/);
var myobjct = new Object();
myobject.PointCount=parseFloat(paramsCoords);
for (var ii=0; ii<fields.length; ii++)
{
var coord=fields[ii].split(/\t/);
//console.info ("X" + coord[0]);
//console.info ("Y" + coord[1]);
var object_Point[ii] = new Object();
object_Point[ii].x_m=parseFloat(coord[0]);
object_Point[ii].y_m=parseFloat(coord[1]);
myobject.Polygon_Point[ii]=object_Point[ii];
}
目前我使用这种结构:
for(var ii = 0; ii
var coord=fields[ii].split(/\t/);
var objPolygon_Point = new Object()
objPolygon_Point["point" + ii] = new Object();
objPolygon_Point["point" + ii].x_m=parseFloat(coord[0]);
objPolygon_Point["point" + ii].y_m=parseFloat(coord[1]);
if (ii=='1')
{
myobject.Polygon_Point1=objPolygon_Point["point" + ii];
}
if (ii=='2')
{
myobject.Polygon_Point2=objPolygon_Point["point" + ii];
}
// ii==3, ii==4, .......
}
答案 0 :(得分:2)
您可以在全局范围内生成动态对象名称,如:
<强>浏览器:强>
var ii = 11
, x = 123
, y = 234;
window['Object_Point' + ii] = {
x : parseFloat(x),
y : parseFloat(y)
}
console.log(Object_Point11);
console.log(window.Object_Point11);
// Object {x: 123, y: 234}
<强>的node.js 强>
> var i = 12;
> global['MyObj'+i] = { hello : 'world' };
> console.log(MyObj12);
> console.log(global.MyObj12);
// { hello: 'world' }
但您可能想要使用自己的window
global
或object
。
> var i = 12, myObj = {};
> myObj['MyObj'+i] = { hello : 'world' };
> console.log(myObj.MyObj12);
// { hello: 'world' }
答案 1 :(得分:0)
我直接用你的例子。我建议创建中间地图对象。即像所有点的持有者之类的东西。使用全局命名空间不是一个好习惯。
var vMsg = req.body.myMessage;
var fields = vMsg.split(/\n/);
var myobjct = new Object();
myobject.PointCount=parseFloat(paramsCoords);
var points = {};
for (var ii=0; ii<fields.length; ii++)
{
var coord=fields[ii].split(/\t/);
//console.info ("X" + coord[0]);
//console.info ("Y" + coord[1]);
var point = points["point" + ii] = new Object();
point.x_m = parseFloat(coord[0]);
point.y_m = parseFloat(coord[1]);
myobject.Polygon_Point[ii] = point;
}