The first four days have covered JavaScript basic syntax, variables, data types, operators/expressions, and conditional statements. Today will learn about loop statements in detail, which are core concepts for implementing repetitive execution in programming. Through loops, large amounts of data and repetitive tasks can be handled efficiently.
π Today's Learning Objectives
- Master the usage of for loops
- Understand the differences between while and do-while loops
- Learn loop control statements (break, continue)
- Understand loop best practices and performance optimization
π for Loops
for loops are the most commonly used loop structure, suitable for situations where the number of iterations is known.
Basic for Loop
// Basic syntax
for (let i = 0; i < 5; i++) {
console.log(`Loop count: ${i}`);
}
// Output: 0, 1, 2, 3, 4
// Reverse loop
for (let i = 5; i > 0; i--) {
console.log(`Reverse: ${i}`);
}
// Output: 5, 4, 3, 2, 1
// Step loop
for (let i = 0; i <= 10; i += 2) {
console.log(`Even numbers: ${i}`);
}
// Output: 0, 2, 4, 6, 8, 10
Components of for Loop
// Initialization; Condition; Update
for (let i = 0; i < 3; i++) {
console.log(`i = ${i}`);
}
// Equivalent to:
let i = 0; // Initialization
while (i < 3) {
// Condition
console.log(`i = ${i}`);
i++; // Update
}
Array Traversal
let fruits = ["apple", "banana", "orange", "grape"];
// Traverse array using for loop
for (let i = 0; i < fruits.length; i++) {
console.log(`${i + 1}. ${fruits[i]}`);
}
// Output:
// 1. apple
// 2. banana
// 3. orange
// 4. grape
π while Loops
while loops are suitable for situations where the number of iterations is uncertain.
Basic while Loop
let count = 0;
while (count < 5) {
console.log(`Count: ${count}`);
count++;
}
// Output: 0, 1, 2, 3, 4
Condition-Driven Loop
// Simulate user input validation
let userInput = "";
let attempts = 0;
const maxAttempts = 3;
while (userInput !== "yes" && attempts < maxAttempts) {
userInput = prompt("Please enter 'yes' to continue:");
attempts++;
console.log(`Attempt count: ${attempts}`);
}
if (userInput === "yes") {
console.log("User confirmed to continue!");
} else {
console.log("Too many attempts, program exits");
}
Infinite Loops and Prevention
// Dangerous infinite loop (don't run)
// while (true) {
// console.log("This will run forever!");
// }
// Safe loop control
let counter = 0;
while (true) {
console.log(`Loop ${counter}`);
counter++;
if (counter >= 5) {
break; // Exit loop
}
}
π do-while Loops
do-while loops execute at least once, suitable for situations where execution happens before judgment.
Basic do-while Loop
let i = 0;
do {
console.log(`do-while: ${i}`);
i++;
} while (i < 3);
// Output: 0, 1, 2
do-while vs while Difference
// while loop - judge first, then execute
let x = 5;
while (x < 5) {
console.log("while loop"); // Won't execute
}
// do-while loop - execute first, then judge
let y = 5;
do {
console.log("do-while loop"); // Will execute once
} while (y < 5);
Practical Application Scenarios
// User menu system
let userChoice;
do {
console.log("\n=== Menu ===");
console.log("1. View information");
console.log("2. Modify settings");
console.log("3. Exit");
userChoice = prompt("Please select operation (1-3):");
switch (userChoice) {
case "1":
console.log("Display user information");
break;
case "2":
console.log("Enter settings page");
break;
case "3":
console.log("Exit program");
break;
default:
console.log("Invalid selection, please re-enter");
}
} while (userChoice !== "3");
π Loop Control Statements
break Statement
break statement is used to immediately exit a loop.
// Using break in for loop
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit loop when i equals 5
}
console.log(i);
}
// Output: 0, 1, 2, 3, 4
// Using break in while loop
let num = 1;
while (true) {
if (num > 10) {
break;
}
console.log(`Number: ${num}`);
num++;
}
continue Statement
continue statement skips the current iteration and continues to the next loop.
// Skip even numbers
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(`Odd number: ${i}`);
}
// Output: 1, 3, 5, 7, 9
// Skip specific values
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 5) {
continue; // Skip number 5
}
console.log(numbers[i]);
}
Label Statements
Label statements are used to control nested loops.
// Use labels to break out of nested loops
outerLoop: for (let i = 0; i < 3; i++) {
innerLoop: for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outerLoop; // Break out of outer loop
}
console.log(`i=${i}, j=${j}`);
}
}
// Output: i=0,j=0 i=0,j=1 i=0,j=2 i=1,j=0
// Use labels to continue outer loop
outerLoop: for (let i = 0; i < 3; i++) {
innerLoop: for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
continue outerLoop; // Continue outer loop's next iteration
}
console.log(`i=${i}, j=${j}`);
}
}
π― Advanced Loop Usage
for...in Loop
Used to traverse enumerable properties of objects.
let person = {
name: "John",
age: 25,
city: "New York",
};
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
// Output:
// name: John
// age: 25
// city: New York
// Traverse array (not recommended)
let fruits = ["apple", "banana", "orange"];
for (let index in fruits) {
console.log(`${index}: ${fruits[index]}`);
}
// Output: 0: apple, 1: banana, 2: orange
for...of Loop
Used to traverse iterable objects (arrays, strings, etc.).
// Traverse array
let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
console.log(fruit);
}
// Output: apple, banana, orange
// Traverse string
let text = "Hello";
for (let char of text) {
console.log(char);
}
// Output: H, e, l, l, o
// Traverse Map
let map = new Map([
["name", "John"],
["age", 25],
["city", "New York"],
]);
for (let [key, value] of map) {
console.log(`${key}: ${value}`);
}
Nested Loops
// Print multiplication table
for (let i = 1; i <= 9; i++) {
let row = "";
for (let j = 1; j <= i; j++) {
row += `${j} Γ ${i} = ${i * j}\t`;
}
console.log(row);
}
// Two-dimensional array traversal
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(`matrix[${i}][${j}] = ${matrix[i][j]}`);
}
}
π― Practice Exercises
Exercise 1: Number Game
function numberGame() {
let target = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
let maxAttempts = 7;
console.log("Welcome to the number guessing game!");
console.log("I'm thinking of a number between 1 and 100, can you guess it?");
while (attempts < maxAttempts) {
let guess = parseInt(
prompt(`Guess ${attempts + 1} (${maxAttempts - attempts} attempts left):`)
);
attempts++;
if (isNaN(guess)) {
console.log("Please enter a valid number!");
attempts--; // Don't count as attempt
continue;
}
if (guess === target) {
console.log(
`π Congratulations! You guessed it! The number is ${target}`
);
console.log(`You guessed it in ${attempts} attempts!`);
return;
} else if (guess < target) {
console.log("Too small!");
} else {
console.log("Too big!");
}
}
console.log(`Game over! The correct answer is ${target}`);
}
// numberGame(); // Uncomment to run the game
Exercise 2: Array Processing Tool
function arrayProcessor(arr) {
if (!Array.isArray(arr)) {
return "Input must be an array";
}
let result = {
sum: 0,
average: 0,
max: arr[0],
min: arr[0],
evenNumbers: [],
oddNumbers: [],
duplicates: [],
};
// Calculate sum, max, min
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] !== "number") {
continue; // Skip non-numeric elements
}
result.sum += arr[i];
result.max = Math.max(result.max, arr[i]);
result.min = Math.min(result.min, arr[i]);
if (arr[i] % 2 === 0) {
result.evenNumbers.push(arr[i]);
} else {
result.oddNumbers.push(arr[i]);
}
}
// Calculate average
result.average = result.sum / arr.length;
// Find duplicate elements
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j] && !result.duplicates.includes(arr[i])) {
result.duplicates.push(arr[i]);
}
}
}
return result;
}
// Test array processor
let testArray = [1, 2, 3, 4, 5, 2, 6, 7, 8, 3, 9, 10];
let result = arrayProcessor(testArray);
console.log("Array processing result:", result);
Exercise 3: Prime Number Detector
function isPrime(num) {
if (num < 2) return false;
if (num === 2) return true;
if (num % 2 === 0) return false;
for (let i = 3; i <= Math.sqrt(num); i += 2) {
if (num % i === 0) {
return false;
}
}
return true;
}
function findPrimesInRange(start, end) {
let primes = [];
for (let i = start; i <= end; i++) {
if (isPrime(i)) {
primes.push(i);
}
}
return primes;
}
function printPrimeTable(max) {
console.log("Prime table (first " + max + " primes):");
let count = 0;
let num = 2;
while (count < max) {
if (isPrime(num)) {
count++;
console.log(`${count}. ${num}`);
}
num++;
}
}
// Test prime functions
console.log("Is 15 prime?", isPrime(15));
console.log("Is 17 prime?", isPrime(17));
let primes = findPrimesInRange(1, 50);
console.log("Primes between 1 and 50:", primes);
printPrimeTable(10);
π Today's Key Points Summary
- for loops: Suitable for known number of iterations
- while loops: Suitable for uncertain number of iterations
- do-while loops: Execute at least once, suitable for execute-then-judge situations
- Loop control: break exits loop, continue skips current iteration
- Advanced loops: for...in traverses objects, for...of traverses iterable objects
π Tomorrow's Preview
Tomorrow will learn about function basics, including:
- Function definition and calling
- Parameters and return values
- Function expressions and arrow functions
- Function scope
π‘ Learning Tips
- Choose appropriate loops: Select the most suitable loop type based on specific needs
- Avoid infinite loops: Ensure loops have clear exit conditions
- Use break and continue: Use loop control statements appropriately
- Consider performance: Pay attention to performance optimization in nested loops
This concludes the introduction to day five's learning content. Tomorrow will continue learning about function basics.
Top comments (0)