GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing en.wikibooks.org — JavaScript/Loops - Wikibooks, open books for an open world
JavaScript supports the repetitive execution of code blocks via the keywords for (;;) {}The syntax of the
for (let i = 0; i < 10; i++) { // a block of statements } An example: Show the series of even numbers multiplied by itself (power 2); show the sum of the numbers from 0 to 10. "use strict"; const upperLimit = 10; let sum = 0; let tmpString = ""; for (let i = 0; i <= upperLimit; i++) { sum = sum + i; if (i % 2 === 0) { tmpString += i*i + "; " } } alert ("The sum is: " + sum + ". The square numbers are: " + tmpString); Optional syntax partsThe "use strict"; // an infinite loop if you do not terminate it with 'break' (see below) for (;;) { // ... break; } const answer = prompt("With which start value shall the loop begin?"); let i = Number(answer); for (; i >= 0 && i < 10; i++) { // the start value is computed above the loop } for (let i = 0; i < 10; ) { // ... if (true) { // an arbitrary other condition to control the increment i++; } } Nesting
"use strict"; const maxInner = 10; const maxOuter = 4; let myString = ""; for (let o = 1; o <= maxOuter; o++) { myString = ""; // Be careful. It's easy to confuse inner and outer loop variables. for (let i = 1; i <= maxInner; i++) { myString = myString + o*i + ", "; } alert(myString); } This nesting of loops is also possible in all the constructs below. continue / breakSometimes only parts or the block shall run. This can be realized by one or more "use strict"; for (let i = 0; i <= 6; i++) { if (i === 5) { continue; // skip the rest of the block } alert(i); // 0, 1, 2, 3, 4, 6 } This example is very simple. It skips the lower part of the block for the case where The "use strict"; for (let i = 0; i <= 6; i++) { if (i === 5) { break; // terminal the loop } alert(i); // 0, 1, 2, 3, 4 } A realistic scenario is a loop over the result of a database search where the connection to the database is broken in the middle of the loop. You can use do {} while ()The syntax of the statement is:
"use strict"; let counter = 100; do { counter++; alert(counter); // ... or some logging } while (counter < 10); while () {}The syntax of for (x in Object) {}This language construct is intended to iterate over the properties of an object. Its syntax is: "use strict"; const myObj = {firstName: "Marilyn", familyName: "Monroe", born: 1953}; for (const key in myObj) { alert(key); // firstName, familyName, born // alert(myObj[key]); // if you want to see the values } Arrays are specialized objects. Hence, it is possible to use the "use strict"; const myArray = ["cero", "uno", "dos", "tres"]; for (const key in myArray) { alert(key); // 0, 1, 2, 3 // alert(myArray[key]); // if you want to see the values } Arrays also accept non-numeric keys, e.g., See also: MDN: for..in for (x of Array) {}This language construct is intended to iterate over an array. Its syntax is: This definition sounds similar to the above definition of the
"use strict"; const myArray = ["cero", "uno", "dos", "tres"]; myArray["four"] = "cuatro"; for (const myValue of myArray) { alert(myValue); // cero, uno, dos, tres. No 'cuatro' because the key is a string. } See also: MDN: for..of for..in vs. for..ofThe differences between the two language constructs are summarized in an example. "use strict"; const myObj = {firstName: "Marilyn", familyName: "Monroe", born: 1953}; const myArray = ["cero", "uno", "dos", "tres"]; myArray["four"] = "cuatro"; // for..of not allowed on true objects; only for..in is possible. for (const x of myObj) {}; // error for (const x in myArray) { alert(x); // 0, 1, 2, 3, four } for (const x of myArray) { alert(x); // cero, uno, dos, tres. NO cuatro! } Object.entries() methodIf you are looking for a loop that processes both keys and values of an object, there is a more straightforward method than the above-shown combination of the "use strict"; const myObj = {firstName: "Marilyn", familyName: "Monroe", born: 1953}; const myArray = ["cero", "uno", "dos", "tres"]; myArray["four"] = "cuatro"; for (const [key, val] of Object.entries(myObj)) { alert(key + ' / ' + val); } for (const [key, val] of Object.entries(myArray)) { alert(key + ' / ' + val); // 'four / cuatro' is included } Hint: The Array.forEach() methodThe data type Array offers the method The method invocation is very easy: The first example shows the function call explicitly. It defines the function myFunction which also takes a single argument. When myFunction is called by forEach(), the next array element is inserted as the argument to myFunction. "use strict"; // function definition (the function is not called here!) function myFunction(element) { alert("The element of the array is: " + element) }; // a test array const myArray = ['a', 'b', 'c']; // iterate over the array and invoke the function once per array element myArray.forEach(myFunction); The following examples show some abbreviations of the function invocation syntax. "use strict"; // the 'arrow' syntax const myFunction = (element) => { alert("The element of the array is: " + element) }; // same code without line breaks: // const myFunction = (element) => {alert("The element of the array is: " + element)}; const myArray = ['a', 'b', 'c']; myArray.forEach(myFunction); "use strict"; const myArray = ['a', 'b', 'c']; // Define the function directly as the argument of the forEach(). Such // functions are called 'anonymous' functions. myArray.forEach((element) => {alert("The element of the array is: " + element)}); "use strict"; const myArray = ['a', 'b', 'c']; // in simple cases, more syntactical elements are optional myArray.forEach(element => alert("The element of the array is: " + element)); It depends on your preference, which syntax you use. In many cases, the called function performs side effects like logging. To calculate values over all array elements, it is necessary to use the technique of closures. In the following example, the variable "use strict"; const myArray = [3, 0, -1, 2]; let sum = 0; myArray.forEach(element => sum = sum + element); alert(sum); All in all, the following rules apply to the
See also: ExercisesSee also |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |