TIL coding
  • Initial page
  • 排版
  • Flexbox
  • Grid
  • jQuery
  • Untitled
  • JavaScript
    • An Introduction to JavaScript
    • Hello, world!
    • Code structure
    • The modern mode, "use strict"
    • Variables
    • Data types
    • Type Conversions
    • Operators
    • Comparisons
    • Interaction: alert, prompt, confirm
    • Conditional operators: if, '?'
    • Logical operators
    • Loops: while and for
    • The "switch" statement
    • Functions
    • Function expressions and arrows
    • JavaScript specials
    • Comments
    • Ninja code
    • Automated testing with mocha
    • Polyfills
    • Objects
    • Garbage collection
    • Symbol type
    • Object methods, "this"
    • Object to primitive conversion
    • Constructor, operator "new"
    • Methods of primitives
    • Numbers
    • Strings
    • Arrays
    • Array methods
    • Iterables
    • Map, Set, WeakMap and WeakSet
    • Object.keys, values, entries
    • Destructuring assignment
    • Date and time
    • JSON methods, toJSON
    • Recursion and stack
    • Rest parameters and spread operator
    • Closure
    • The old "var"
    • Global object
    • Function object, NFE
    • The "new Function" syntax
    • Scheduling: setTimeout and setInterval
    • Decorators and forwarding, call/apply
    • Function binding
    • Currying and partials
    • Arrow functions revisited
    • Property flags and descriptors
    • Property getters and setters
    • Prototypal inheritance
    • F.prototype
    • Native prototypes
    • Prototype methods, objects without __proto__
    • The “class” syntax
    • Class inheritance
    • Static properties and methods
    • Private and protected properties and methods
    • Extending built-in classes
    • Class checking: "instanceof"
    • Mixins
    • Error handling, "try..catch"
    • Custom errors, extending Error
    • Introduction: callbacks
    • Promise
    • Promises chaining
    • Error handling with promises
    • Promise API
  • Bootstrap
    • Navbar
Powered by GitBook
On this page
  • The “while” loop
  • The “do…while” loop
  • The “for” loop
  • Breaking the loop
  • Continue to the next iteration
  • Labels for break/continue

Was this helpful?

  1. JavaScript

Loops: while and for

The “while” loop

無限迴圈,當判斷式為真,迴圈會持續執行,直到判斷式為錯誤。

while (condition) {
  // code
  // so-called "loop body"
}

let i = 0;
while (i < 3) { // shows 0, then 1, then 2
  alert( i );
  i++;
}

// single line omit {...}
let i = 3;
while (i) alert(i--);

The “do…while” loop

迴圈至少執行一次。

do {
  // loop body
} while (condition);

let i = 0;
do {
  alert( i );
  i++;
} while (i < 3);

The “for” loop

for (begin; condition; step) {
  // ... loop body ...
}

for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2
  alert(i);
}

變數被宣告在迴圈裡面,只能在迴圈內使用,除非使用變數為全域變數。

for (let i = 0; i < 3; i++) {
  alert(i); // 0, 1, 2
}
alert(i); // error, no such variable

// global variable
let i = 0;

for (i = 0; i < 3; i++) { // use an existing variable
  alert(i); // 0, 1, 2
}

alert(i); // 3, visible, because declared outside of the loop

for 迴圈可以忽略任何部分,但;要存在不然會有 syntax error。

let i = 0; // we have i already declared and assigned

for (; i < 3; i++) { // no need for "begin"
  alert( i ); // 0, 1, 2
}

let i = 0;

for (; i < 3;) {
  alert( i++ );
}

Breaking the loop

用 break 可以離開迴圈。

let sum = 0;

while (true) {
  let value = +prompt("Enter a number", '');
  if (!value) break; // (*)
  sum += value;
}

alert( 'Sum: ' + sum );

Continue to the next iteration

用 continue 可以停止當次運算,開始下次運算。

for (let i = 0; i < 10; i++) {
  // if true, skip the remaining part of the body
  if (i % 2 == 0) continue;
  alert(i); // 1, then 3, 5, 7, 9
}

// same, side-effect less readability
for (let i = 0; i < 10; i++) {
  if (i % 2) {
    alert( i ); // if there are multi lines to execute
  }
}

在 ? operator 不能使用 break / continue 。

if (i > 5) { // worked
  alert(i);
} else {
  continue;
}

// same
(i > 5) ? alert(i) : continue; // continue isn't allowed here

Labels for break/continue

label 停止巢狀迴圈,用 break 只能停止一個迴圈。

outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    let input = prompt(`Value at coords (${i},${j})`, '');
    // if an empty string or canceled, then break out of both loops
    if (!input) break outer; // (*)
    // do something with the value...
  }
}

alert('Done!');

PreviousLogical operatorsNextThe "switch" statement

Last updated 5 years ago

Was this helpful?