Q
Q
qo_0p2015-11-07 16:01:04
JavaScript
qo_0p, 2015-11-07 16:01:04

Unusual use of for or how does it work?

I came across a code with a non-standard use of the for loop (see the first loop) I tried to comprehend, but something doesn’t work. Guys, can you explain what this design is and how it works? jsfiddle link

var canvas = document.body.appendChild(document.createElement("CANVAS")),ctx = canvas.getContext("2d"), starList = [], approx = 0.05, x_center = canvas.width >> 1, y_center = canvas.height >> 1, STAR_COUNT = 256, SCATTER = 50, SCALE = 2.5, DEPTH = 15, INIT_STAR_RANGE = 25, UPDATE_TIME = 16.666;//1

for(var i = STAR_COUNT; i--; starList.push({x: -INIT_STAR_RANGE + ((Math.random() * 2*INIT_STAR_RANGE) | 0), y: -INIT_STAR_RANGE + ((Math.random() * 2*INIT_STAR_RANGE) | 0), z: 1 + Math.random() * DEPTH}));//2

setInterval(function(){ctx.fillStyle = "#000"; //3
                       
ctx.fillRect(0, 0, canvas.width, canvas.height); //4
                       
for (i = 0; i < STAR_COUNT; ++i){((starList[i].z -= approx) < approx) && (starList[i] = {x: -INIT_STAR_RANGE + ((Math.random() * 2*INIT_STAR_RANGE) | 0),y: -INIT_STAR_RANGE + ((Math.random() * 2*INIT_STAR_RANGE) | 0),z: DEPTH}); //5
                                 
var shade = Math.floor((1 - starList[i].z / DEPTH) * 255); //6
 
ctx.beginPath(); //7
                                 
ctx.fillStyle = "rgb(" + shade + "," + shade + "," + shade + ")"; //8
                                 
ctx.arc(x_center + starList[i].x * (SCATTER / starList[i].z), y_center + starList[i].y * (SCATTER / starList[i].z), (1 - starList[i].z / DEPTH) * SCALE, 0, 2 * Math.PI, true); //9
                                 
ctx.fill(); //10
                                 
} //11
                       
}, UPDATE_TIME); //12

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yaroslav Lyzlov, 2015-11-07
@qo_0p

for ([initial-expression]; [condition]; [final-expression])
statement

initial-expression // i = START_COUNT просто выражение
condition - выражение, которое вычисляется между операциями, пока true, следующая операция запускается, если false, то цикл закончится -//  i--, когда i станет 0, то мы выйдем из цикла
final-expression - выражение, которое выполняется после очередной итерации и всё

Can be rewritten like this
for (var i = START_COUNT; i > 0; i--) { 
   starList.push...
}

For what ... just wanted ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question