# JavaScript 中的計數器

Sahil Bhosale 2024年2月15日

## 在 JavaScript 中使用變數實現計數器

``````function value() {
let counter = 0;
let randomNo = Math.floor(Math.random() * (10 - 0 + 1) + 0);

while (randomNo != 5) {
randomNo = Math.floor(Math.random() * (10 - 0 + 1) + 0);
counter += 1;
}
return counter;
}

console.log('Counter value is', value());
``````

`while` 迴圈內，我們有一個條件，用於檢查生成的隨機數是否等於 `5`。如果不是這種情況，我們將增加計數器，以便 `while` 迴圈將繼續執行。如果條件為假，即生成的隨機數等於 `5`，則 `value()` 函式將返回計數器變數的值。

``````Counter value is 23
``````

## 在 JavaScript 中使用會話儲存實現計數器

``````for (let i = 0; i < 5; i++) {
value();
}

function value() {
let counter = 0;
console.log('Counter Value:', counter + 1);
}
``````

``````Counter Value: 1
Counter Value: 1
Counter Value: 1
Counter Value: 1
Counter Value: 1
``````

`setItem()` 方法有兩個引數，鍵和值。這兩個引數都是字串。在這種情況下，鍵將是 `counter`（你可以為鍵提供任何名稱），並且值將設定為 `0`

``````window.onunload = () => sessionStorage.clear();

for (let i = 0; i < 5; i++) {
value();
}

function value() {
if (sessionStorage.getItem('counter') == null)
sessionStorage.setItem('counter', '0');

let counterValue = Number(sessionStorage.getItem('counter'))
sessionStorage.setItem('counter', counterValue + 1);

console.log('Counter Value:', sessionStorage.getItem('counter'));
}
``````

``````Counter Value: 1
Counter Value: 2
Counter Value: 3
Counter Value: 4
Counter Value: 5
``````

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.