数组中的变量 - Javascript

时间:2013-03-22 15:24:49

标签: arrays variables

我正在尝试将变量cord1x和cord1y放入段数组中,但它确实有效。

这是我的代码:

var cord1x = 121; 
var cord1y = 446;  
segments = [{x: cord1x, y: cord1y}];

我如何成为segements字符串中的变量?

3 个答案:

答案 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].xcord2x可以访问segments[0].y

使用segments = {x: cord1x, y: cord1y}segments成为包含属性xy的对象。 cord1可以访问segments.xcord2可以访问segments.y

使用segments = [cord1x, cord1y]segments成为两个整数的数组。 cord1x可以访问segments[0]cord1y可以访问segments[1]

使用segments = '{x: '+cord1x+', y: '+cord1y+'}'segments成为{x:121, y:446}形式的字符串。不利的一面是,cord1xcord1y并不容易进行检索。好处是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)

您可以在w3学校http://www.w3schools.com/jsref/jsref_push.asp

了解更多信息

答案 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;
};