2014-06-22 112 views
0

下面的每條語句都做了什麼? 'col'是數組的內置屬性嗎?下面的.forEach語句做了什麼?

var width = data.length, height = data[0].length; 
    data.forEach(function(col){ 
    col.forEach(function(val){ 
     geometry.vertices.push(new THREE.Vector3(val.x,val.y,val.z)) 
     colors.push(getColor(2.5,0,val.z)); 
    }); 
    }); 

在一些情況下,前面的代碼的需要:

var data = new Array(); 
    for(var x=BIGIN;x<END;x++){ 
    var row = []; 
    for(var y=BIGIN;y<END;y++){ 
     z = 2.5*(Math.cos(Math.sqrt(x*x+y*y))+1); 
     row.push({x: x, y: y, z: z}); 
    } 
    data.push(row); 
    } 
+0

看到這裏https://developer.mozilla.org/en-US/docs/Web/JavaScript的/參考/ Global_Objects /陣列/的forEach – elclanrs

回答

1

Array.forEach遍歷陣列,就像一個for迴路。

array.forEach(function(indice) {}); 

data陣列陣列的,col是從第一forEach傳遞的參數,所以內部data第二forEach迭代陣列。

很明顯在創建data以及

var data = []; // data is an array 
... 
var row = []; // row is an array 
for(var ...){ 
    // do stuff 
} 
data.push(row); // put one array inside the other 

代碼,然後它的迭代

data.forEach(function(col){ // <- col is passed as the argument 
    col.forEach(function(val){ 
     // do stuff 
    }); 
});