2014-06-22 3 views
0

Que font les deux instructions forEach ci-dessous? Est-ce que 'col' est une propriété intégrée pour les tableaux?Que font les instructions .forEach ci-dessous?

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)); 
    }); 
    }); 

En cas une partie du code précédent est nécessaire:

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

Voir ici https://developer.mozilla.org/en-US/docs/Web/JavaScript/Référence/Global_Objects/Array/forEach – elclanrs

Répondre

1

Array.forEach itère sur un tableau, comme une boucle for.

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

dataest un tableau de tableaux, col est l'argument passé de la première forEach, de sorte que les deuxièmes matrices de forEach itère l'intérieur data.

Il est évident dans le code qui crée data ainsi

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 

puis il est itérer

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