<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
//basic while
let i = 0
while (confirm('continue?')){
alert(`${i} repeat`)
i = i+1
}
//while + array
const array = [1,2,3,4,5]
while(i < array.length){
console.log(`${i} : ${array[i]}`)
i++
}
</script>
</head>
<body>
</body>
</html>
### Basic `while` Loop with User Confirmation
- Initializes a counter variable `i` to `0`.
- Enters a `while` loop that continues as long as the user clicks the "OK" button in a confirmation dialog box prompted by `confirm('continue?')`.
- Inside the loop, an `alert` displays the current value of `i` followed by the word "repeat", then increments `i` by `1`.
- This loop demonstrates how to perform repetitive actions with user interaction controlling the continuation of the loop. It keeps running until the user decides to stop it by clicking the "Cancel" button in the confirmation dialog.
### `while` Loop Iterating Over an Array
- Utilizes the same counter `i`, which now represents the index of elements in the array `array` containing the numbers 1 to 5.
- The loop condition checks if `i` is less than the length of `array`, ensuring that the loop iterates over each element of the array.
- Inside the loop, `console.log` prints the current index `i` and the value at that index `array[i]`, then increments `i`.
- This loop shows how to iterate through an array when the total number of iterations is determined by the array's length.
### Observations and Output
- The first part uses `alert` and `confirm` dialog boxes for a basic interactive loop, stopping based on user response.
- The second part prints to the console each element of the array alongside its index. Since this part directly follows the first and uses the same `i` variable without resetting it, the starting index for the array iteration will be where the first loop left off (the value of `i` after the user stops the first loop).
- If you wish for the array iteration to always start from the beginning of the array regardless of the first loop, you should reset `i` to `0` before the array loop starts.
### Note on Output
- The output from the first loop appears as alert dialogs on the page, requiring user interaction to proceed.
- The output from the array iteration will only be visible in the browser's developer console. To view it, you would need to open the console (usually accessible by pressing F12 or right-clicking the page and selecting "Inspect" or "Inspect Element", then navigating to the "Console" tab). This approach is useful for debugging or displaying information during development rather than for user interaction in a production environment.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
chapter 5) arguments (0) | 2024.12.03 |
---|---|
chapter 4) for (0) | 2024.12.02 |
chapter 4) continue (0) | 2024.11.30 |
chapter 4) break (0) | 2024.11.29 |
chapter 3) Using nested conditionals (0) | 2024.11.28 |