iT邦幫忙

2025 iThome 鐵人賽

DAY 13
0

我們已經認識了資料型別的分類,這一篇要深入探討最常用的一種:數字(Number)

  • JavaScript中的 Number 可以同時表示整數與浮點數(帶小數點的數字),
    並且支援多種運算與方法。

基本使用與轉型

數字型別最直覺的用途,就是數學運算。

var catCounts = 10;
var oneMoreCat = catCounts + 1; // 11
var oneLessCat = catCounts - 1; // 9
var doubleCat = catCounts * 2;  // 20
var halfCat = catCounts / 2;    // 5

有時候我們需要把字串轉成數字,常見的方法有:

Number("20");        // 20
parseInt("10");      // 10
parseInt("1.23");    // 1
parseFloat("1.23");  // 1.23
+"20";               // 20 (一元加號會嘗試轉成數字)

常見的運算子

JavaScript 的數字支援各種數學運算:

  • 算術運算+/%(餘數)、*(次方)
  • 增減運算++--
  • 賦值運算+===/=
let x = 10;
x++;   // 11
x--;   // 10
x /= 2 // 5

比較運算子(Comparison Operators)

比較運算子會回傳布林值:

console.log(3 == "3");   // true,值相等
console.log(3 === "3");  // false,型別不同
console.log(3 !== "3");  // true,型別不同
console.log(5 >= 3);     // true

邏輯運算子(Logical Operators)

邏輯運算子常搭配條件判斷:

  • &&(AND):兩邊都為 true 才為 true。
  • ||(OR):其中一邊為 true 即為 true。
  • !(NOT):反轉布林值。
console.log(5 > 3 && 100 > 99); // true
console.log(0 || 10);           // 10(短路特性)
console.log(300 && 13);         // 13(短路特性)

位元運算子(Bitwise Operators)

數字在底層會被轉成 32 位元二進位進行位元運算。

let a = 10; // 1010
let b = 9;  // 1001

console.log(a & b); // 8  (1000) 
console.log(a | b); // 11 (1011)
console.log(a ^ b); // 3  (0011)

位移運算:

  • a << b:左移
  • a >> b:右移
  • ~a:位元取反

NaN(Not a Number)

當運算失敗或無法轉成數值時,會得到 NaN

typeof 10; // "number"
Number("10abc"); // NaN
typeof NaN; // "number"

雖然叫「Not a Number」,但它本身仍然是 number 型別。

常用 Number 方法

JavaScript 的數字在設計上也是一種物件,因此擁有方法:

let age = 27;
console.log(age.toString());   // "27"
console.log(typeof age.toString()); // "string"

const pi = 3.1415926;
console.log(pi.toFixed(2));    // "3.14"
  • 注意:電腦對小數的表示並不精確,像 0.1 + 0.2 === 0.3 會是 false

運算子的相依性與優先序

  • 相依性(Associativity)
    • =(賦值運算子)是 右相依性,從右到左計算。
    • &&|| 等邏輯運算子是 左相依性,從左到右計算。
let a = 1, b = 2, c = 3;
a = b = c;
console.log(a, b, c); // 3 3 3
  • 優先序(Precedence)
    • 先乘除,後加減。
    • 括號擁有最高優先序。
console.log(1 + 2 * 3);     // 7
console.log((1 + 2) * 3);   // 9

參考資料


上一篇
Day12|變數(Variable)
下一篇
Day14|字串(String)
系列文
程式小白的 30 天轉職挑戰14
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言