2012-11-02 24 views
2

我看在three.js所代碼,特別是THREE.SphereGeometry方法創建一個球體: https://github.com/mrdoob/three.js/blob/master/src/extras/geometries/SphereGeometry.js關聯數組查找(從three.js所代碼)

有2套環 - 我在看第二個。

我的問題是這樣的: 有一個創建陣列,稱爲頂點數組。在這個數組中添加對象數組。

後來,一個單一的對象是使用索引檢索,具體如下:

var v1 = vertices[ y ][ x + 1 ]; 

然後,略低於這一點,它出現在對象再次引用但這個語法:

var n1 = this.vertices[ v1 ].clone().normalize(); 

嘗試爲可以的話,這似乎是對我的錯誤..不會this.vertices[v1]回報不確定的?

回答

3

認爲是什麼讓這個混亂是this.vertices VS vertices。它們實際上是兩種不同的結構。

// first loop 
for (...) { 
    /* ... */ 

    // this.verticies will have every vertex 
    this.vertices.push(vertex); 

    verticesRow.push(this.vertices.length - 1); 
    /* ... */ 
} 

// notice we pushed a row of vertices to `vertices` not `this.verticies` 
vertices.push(verticesRow); 


// second loop 
for (...) for (...) { 
    // grab the vertex from the local list 
    var v1 = vertices[ y ][ x + 1 ]; 

    // use it to grab something from the object's list 
    var n1 = this.vertices[ v1 ].clone().normalize(); 
} 
+0

啊!衛生署!我應該抓住那個。謝謝! – desau

+0

爲什麼你應該避免重複使用的變量名稱一個很好的例子 - 它混淆了別人誰將會與您的代碼工作 – slebetman

0

我不知道這件事具體的例子,但這裏是一個人爲的數據結構,將是有效的,而不一定是錯誤。

x = 1 
y = 2 

vertices = ["","",["","x",3],"the third element"] 

var v1 = vertices[y][x+1] // v1 is `3` 

var n1 = this.vertices[v1] 

alert(n1) 
// alerts `the third element` 
+0

真,但OP說:「後來,一個對象被檢索利用指標,特別是」 ......「VAR V1 =頂點[......」(不是int) – Ian

+0

原理相同:'頂點= [{},{},{2:3},{一個: 「b」}]'...'警報(n1.a)''警報B'。重點是內部對象可以包含外部數組中另一個對象的索引。 –

+0

這是沒有意義的 - 在OP說,一個對象被檢索...你不能一個對象傳遞給'[]'索引的數組。你是對的,一個對象的屬性可以包含一個索引,但是當OP說「一個對象被檢索到」時,那沒關係...... – Ian