2013-03-22 71 views
-2

我試圖將變量cord1x和cord1y放入段數組中,但它可以工作。數組中的變量 - Javascript

這裏是我的代碼:

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

我如何成爲變量引入鏈段字符串?

+0

_「它不工作」_是什麼意思? – 2013-03-22 15:25:34

+0

'segments'是一個包含一個對象的數組。定義「不起作用」。 – 2013-03-22 15:25:54

+0

我完全不理解最後一段。 「我如何成爲」似乎意味着你變成了別的東西,這顯然不是在這裏。 – 2013-03-22 15:28:17

回答

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

With segments = [cord1x, cord1y]segments成爲兩個整數的數組。 cord1x變爲可訪問,因爲segments[0]cord1y變得可訪問爲segments[1]

With segments = '{x: '+cord1x+', y: '+cord1y+'}'segments成爲形式爲{x:121, y:446}的字符串。缺點是cord1xcord1y不容易檢索。好處是segments現在可以通過使用===進行比較而不是身份相等。

+0

嘿嘿。非常感謝你!這對我幫助很大。你的第二個評論是我尋找的。 :) – paul 2013-03-22 15:50:37

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

+0

我不建議引用w3schools。改用MDN。網站上有很多可怕的建議。另外,你爲什麼在你的例子中使用水果(除了因爲這個例子是從該網站複製粘貼)? – 2013-03-22 15:43:29

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; 
}; 
+0

你知道'Coordinates.onLoad'永遠不會被調用,除非手動嗎? – 2013-03-22 15:53:46