2013-03-14 64 views
0

我有一個使用Three.js爲3D對象着色的函數。我的變量j存在,如果我使用alert(j)它的作品,但是當我使用變量作爲我的數組(索引顏色映射)它不。爲什麼我的變量「j」未定義?

colormap=[[0,0,0.5625],[0,0,0.625],[0,0,0.6875],[0,0,0.75],[0,0,0.8125],[0,0,0.875],[0,0,0.9375],[0,0,1],[0,0.0625,1],[0,0.125,1],[0,0.1875,1],[0,0.25,1],[0,0.3125,1],[0,0.375,1],[0,0.4375,1],[0,0.5,1],[0,0.5625,1],[0,0.625,1],[0,0.6875,1],[0,0.75,1],[0,0.8125,1],[0,0.875,1],[0,0.9375,1],[0,1,1],[0.0625,1,0.9375],[0.125,1,0.875],[0.1875,1,0.8125],[0.25,1,0.75],[0.3125,1,0.6875],[0.375,1,0.625],[0.4375,1,0.5625],[0.5,1,0.5],[0.5625,1,0.4375],[0.625,1,0.375],[0.6875,1,0.3125],[0.75,1,0.25],[0.8125,1,0.1875],[0.875,1,0.125],[0.9375,1,0.0625],[1,1,0],[1,0.9375,0],[1,0.875,0],[1,0.8125,0],[1,0.75,0],[1,0.6875,0],[1,0.625,0],[1,0.5625,0],[1,0.5,0],[1,0.4375,0],[1,0.375,0],[1,0.3125,0],[1,0.25,0],[1,0.1875,0],[1,0.125,0],[1,0.0625,0],[1,0,0],[0.9375,0,0],[0.875,0,0],[0.8125,0,0],[0.75,0,0],[0.6875,0,0],[0.625,0,0],[0.5625,0,0],[0.5,0,0]]; 

j = 0;// indice colore nella matrice 

var callbackMale = function (geometry, materials) 
{ 
    // surf contain surface 
    var cmin=surf.min(), cmax=surf.max(), colorLength=colormap.length; 

    for (var i = 0, l = geometry.vertices.length; i < l; i ++) 
    { 

    var face = geometry.faces[ i ]; 
    j = Math.round(((surf[i]-cmin)/(cmax-cmin)*colorLength)); 

    if(j < 0) 
     j=0; 
    else if(j >= colorLength) 
     j=colorLength; 
    alert(j) 
    var ind = colormap[j]; // j undefined    
    for(var k = 0 ; k < 3 ; k++) 
    {    
     face.vertexColors[ k ] = new THREE.Color().setRGB(ind[0],ind[1],ind[2]);     
    }//fine for interno 

    }//fine for esterno 
} 
+0

斑點小無關錯誤:'如果(j> = colorLength)J = colorLength;'應該是'如果(j> = colorLength)J = colorLength - 1;'或者你會在數組的最後一個元素之後結束,因爲數組索引是從零開始的。 – 2013-03-14 10:07:21

+0

它可能是你的Math.round的結果..未定義 – 2013-03-14 10:07:45

+2

它不是j,而是不存在的colormap [j]。如果j = 9,則colormap [9]不存在。 – Diode 2013-03-14 10:09:04

回答

0

j的類型是什麼?整數或浮點數或其他? 我想你嘗試把一個float放入一個int,它不起作用。

+0

我使用返回整數的Math.round。 – 2013-03-14 10:13:57

+0

警報中'j'的值是什麼? – 2013-03-14 10:16:25

0

您的循環將超出數組範圍,導致來自colormap[j]的未定義值。

else if(j >= colorLength) 
    j=colorLength; 

將您的值設置爲數組的邊界,因爲數組是從零開始的。固定最大爲一個下:

else if(j >= colorLength) 
    j=colorLength-1;