---
title: "【JavaScript】JS地下城-3F-計算機"
description: "JS地下城-3f-計算機"
canonical_url: "https://hannoeru.me/posts/javascript-dungeon-3f-calculator"
---

> Index of every page on this site: [llms.txt](https://hannoeru.me/llms.txt)

## 3F-計算機

![wp-image-242](https://hannoeru.me/images/2019/05/screenshot-2019-05-14-23.51.36.png)

### 連結

[Demo](https://gh.hannoeru.me/js-calculator/)

[Code](https://github.com/hannoeru/js-calculator)

### 使用語言

HTML、CSS、JavaScript（ES6）

### BOSS 弱點

1. 【特定技術】數字位數過多時，不能因此而破版，計算機功能皆須齊全
2. 【自我學習】請在此關卡中「自學一個你原本不太會的技巧」，投稿時分享你透過哪些資源學習，並寫範例程式碼講解該技巧，以及你如何應用在此關卡上。

### 技巧

#### 使用 `const` 宣告函式

```js
const func = () => {
  // do something
}
```

#### 三元運算子

使用三元運算子可以大大減少程式碼佔用的行數，也可以提高效能，寫得好可以讓程式碼更好閱讀，寫不好可能連自己都看不懂…

語法：

```js
x ? i : a
```

範例：

```js
// 宣告
const x = true
// true的話回傳i，false的話回傳a
x ? i : a
// 結果回傳i
```

#### `eval()` 函式

> ⚠️ **注意：** `eval()` 會執行任意字串，對使用者輸入使用有安全風險（注入攻擊）。在正式專案中請改用自己寫的解析器或經過嚴格驗證的計算庫（例如 [math.js](https://mathjs.org/)）；本文僅為教學用途。

語法：

```js
// eslint-disable-next-line no-eval
eval(要執行的字串)
```

範例：

```js
const str = '10+4*5'
// eslint-disable-next-line no-eval
const B = eval(str)

console.log(B) // 輸出 30
```

#### 依照文字寬度縮放文字

從 30 開始用 for 加大文字到 56，如果中間超過計算機寬度就設定當前文字大小，為了要符合美觀再 -4，才不會太靠近邊緣。

```js
// 在主函式最後一行執行resizeText()
const resizeText = () => {
  for (let i = 30; i < 56; i++) {
    display.style.fontSize = `${i}px`
    if (display.scrollWidth > calculator.clientWidth) {
      display.style.fontSize = `${i - 4}px`
      break
    }
  }
}
```

#### 在小數點前每3格加一個逗號

使用正規表達式 `\B(?=(\d{3})+(?!\d))` 在每三位數前方插入逗號（作法在下方程式碼中）：

```js
// 在主函式第一行執行addComma(false)消除逗號進入計算
// 在主函式最後一行執行addComma(true)新增逗號到輸出結果
const addComma = (isAdd) => {
  if (isAdd) {
    const parts = display.textContent.split('.')
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    display.textContent = parts.join('.')
  } else {
    display.textContent = display.textContent.replace(/,/g, '')
  }
}
```

### 參考資料

[How to build an HTML calculator app from scratch using JavaScript](https://www.freecodecamp.org/news/how-to-build-an-html-calculator-app-from-scratch-using-javascript-4454b8714b98/)

[JavaScript初級者のためのコーディングガイド](https://qiita.com/raccy/items/bf590d3c10c3f1a2846b)

## Sitemap

See the full [sitemap](https://hannoeru.me/sitemap.md) for all pages.
