我正在尝试将变量cord1x和cord1y放入段数组中,但它确实有效。
这是我的代码:
var cord1x = 121;
var cord1y = 446;
segments = [{x: cord1x, y: cord1y}];
我如何成为segements字符串中的变量?
答案 0 :(得分:1)
根据您的评论,或许Array#push
就是您想要的:
segments = [];
//foreach point in some set
// compute cord1x, cord1y
segments.push({x: cord1x, y: cord1y});
然后segment
成为一个对象数组,每个对象代表一个2d点,与segments = [{x: 121, y: 446}, {x: 164, y: 384}, {x: 190, y: 271}, {x: 186, y:198}, {x: 180, y:60}]
仅基于这个问题:
使用segments = [{x: cord1x, y: cord1y}];
,segments
成为包含一个匿名对象的数组。 cord1x
可以访问segments[0].x
,cord2x
可以访问segments[0].y
。
使用segments = {x: cord1x, y: cord1y}
,segments
成为包含属性x
和y
的对象。 cord1
可以访问segments.x
,cord2
可以访问segments.y
。
使用segments = [cord1x, cord1y]
,segments
成为两个整数的数组。 cord1x
可以访问segments[0]
,cord1y
可以访问segments[1]
。
使用segments = '{x: '+cord1x+', y: '+cord1y+'}'
,segments
成为{x:121, y:446}
形式的字符串。不利的一面是,cord1x
和cord1y
并不容易进行检索。好处是segments
现在可以使用===
来比较平等而不是身份。
答案 1 :(得分:0)
为此你可以在javascript中使用push方法。
var coordinate1 = Coordinates.getCoordinate(100, 200);
var coordinate2 = Coordinates.getCoordinate(200, 300);
var coordinate3 = Coordinates.getCoordinate(300, 400);
var coordinates = [coordinate1, coordinate2];
coordinates.push(coordinate3)
了解更多信息
答案 2 :(得分:0)
这可能有用。
var Coordinates = function() {};
Coordinates.onLoad = function() {
var coordinate1 = Coordinates.getCoordinate(100, 200);
var coordinate2 = Coordinates.getCoordinate(200, 300);
// access them like coordinate1.x, coordinate1.y
};
Coordinates.getCoordinate = function(x, y) {
var coordinate = {
x: x,
y: y
};
return coordinate;
};