最近又開始用 Codewars 來練習刷題,也嘗試開一個 Repository:codewars-challenges 記錄作答結果,蠻喜歡這種能夠慢慢升級的感覺,答題結束還能參考其他人的解法,才恍然大悟原來還有更簡潔的思路。
發現自己對於一些 JavaScript 函式使用還是不太熟,把之前寫過的筆記重新複習過,本篇主要整理 JS 常見的內建函式,列表如下:
- Math.floor(x):無條件捨去,回傳「小於等於」所給數字的最大整數
- Bitwise NOT (~):位元反向運算子(波浪號)
- Math.ceil(x):無條件進位,回傳「大於等於」所給數字的最小整數
- Math.round(x):四捨五入
- toFixed(x):四捨六入五留雙
- Math.sqrt(x):返回一個數的平方根
- Math.abs(x):返回一個數的絕對值
Math.floor(x):無條件捨去,回傳「小於等於」所給數字的最大整數
1 2 3 4 5 6
| Math.floor(.95); Math.floor(4); Math.floor(7.004); Math.floor(-0.95); Math.floor(-4); Math.floor(-7.004);
|
Bitwise NOT (~):位元反向運算子(波浪號)
- Bitwise NOT(
~)作用是將數字 x 轉換為 -(x + 1)
- Double Bitwise NOT(
~~):雙位元元反向運算子(兩個波浪號),對正數的作用類似 Math.floor(x) 的無條件捨去,但對負數則結果不同
1 2 3 4 5 6 7 8 9
| ~10 ~-10 ~10.5 ~-10.5
~~10 ~~-10 ~~10.5 ~~-10.5
|
Math.ceil(x):無條件進位,回傳「大於等於」所給數字的最小整數
1 2 3 4 5
| Math.ceil(.95); Math.ceil(4); Math.ceil(7.004); Math.ceil(-0.95); Math.ceil(-7.004);
|
Math.round(x):四捨五入
1 2 3 4
| Math.round(20.49); Math.round(20.5); Math.round(-20.5); Math.round(-20.51);
|
toFixed(x):四捨六入五留雙
- 以字串返回,精確至「小數點後」的數字,小數部分依指定長度補充零
1 2 3 4 5 6 7 8 9
| 1.23.toFixed(2); 1.234.toFixed(2); 1.235.toFixed(2); 1.236.toFixed(2); 1.244.toFixed(2); 1.245.toFixed(2); 1.246.toFixed(2);
(36).toFixed(4)
|
Math.sqrt(x):返回一個數的平方根
1 2 3 4
| Math.sqrt(2); Math.sqrt(4); Math.sqrt(-2); Math.sqrt(0);
|
Math.abs(x):返回一個數的絕對值
1 2 3 4 5 6 7
| function difference(a, b) { return Math.abs(a - b); }
difference(3, 5); difference(5, 3); difference(-5, -3);
|
Reference
- [JS] JavaScript 運算子(Operator)
- JavaScript 四捨五入、無條件捨去、無條件進位
- 使用 JavaScript 的數字時的常見錯誤