Map Range
Dette rutediagram viser hvordan en løkke fungerer.
flowchart TD
  start((S)) --> init[INITIALIZE]
  init --> cond{CONDITION?}
  cond -->|true| body[LOOP_BODY]
  body --> step[POST_STEP]
  step --> cond
  cond ---->|false| end_loop((E))
  
  classDef termination fill:#fff,stroke:#000,color:#fff,stroke-width:4px;
  class start,end_loop termination
  
  %%classDef myClass fill:#ddd, stroke:#000;
  %%class init,cond,body,step myClass
For løkke
Her er for-løkken vist med pseudokode.
for(INITIALIZE;CONDITION;POST_STEP){
  LOOP_BODY
}Her er et konkret eksempel i javascript, der printer tal fra 0 til 9.
for(let i = 0; i < 10; i++){
  console.log(i);
}While løkke
En anden måde at lave en løkker er ved at bruge while.
INITIALIZE;
while(CONDITION){
  LOOP_BODY;
  POST_STEP;
}Her er eksemplet, der printer tal fra 0 til 9, lavet med en while løkke.
let i = 0
while(i < 10){
  console.log(i);
  i++;
}Eksempel med Løkke
Dette eksempel viser hvordan man kan benytte funktionen map(), til at lave lineær interpolation.
Endepunkternes position kan varieres ved at ændre musemarkørens x-position.
De små cirkler generes i for-løkken, og antallet af cirkler styres af musens y-position.
function setup() {
  createCanvas(windowWidth, windowHeight);
  fill(133, 18, 9);
  stroke(209, 52, 40)
  strokeWeight(3)
}
function draw() {
  background(70);
  // Define tilt based on mouse horizontal position
  const yRange = height / 4
  const deltaY = map(mouseX, 0, width, -yRange, yRange, true)
  
  // Define control points
  const ax = 50
  const ay = height / 2 - deltaY
  const bx = width - ax
  const by = height / 2 + deltaY
  // Draw large cirles at control poins
  const diameter = 50
  circle(ax, ay, diameter)
  circle(bx, by, diameter)
  // Define number of circles based on mouse vertical position
  let n = map(mouseY, 0, height, 30, 2, true)
  n = ceil(n)
  // Draw circles using a loop
  for (let i = 0; i <= n; i++) {
    const x = map(i, 0, n, ax, bx)
    const y = map(i, 0, n, ay, by)
    circle(x, y, diameter / 2)
  }
}Demo
Prøv det kørende eksempel
Materiale
- Loops: while and for - Javascript tutorial
 - for - MDN docs
 - setup()
 - createCanvas()
 - draw()
 - fill()
 - stroke()
 - strokeWeight()
 - background()
 - map()
 - line()
 - circle()