JavaScript中的數據類型

JavaScript中的數據類型

本文解釋了JavaScript中的數據類型。

YouTube Video

JavaScript中的數據類型

JavaScript具有用於分類值的數據類型,大致分為基本類型對象類型。數據類型決定了變量中存儲的數據類型,並影響它可以如何被操作。

基本型別

基本類型是表示單一值的簡單數據類型。JavaScript具有以下7種基本類型。

number

1let num = 42;
2let pi = 3.14;
3
4console.log("Value of num:", num);
5console.log("Value of pi:", pi);
  • number是一種用於處理數值(包括整數和浮點數(小數))的類型。處理超過特定限制的值會導致InfinityNaN(非數值)。
1// Decimal calculations
2console.log(0.1 + 0.2 === 0.3); // false
3console.log(0.1 + 0.2); // 0.30000000000000004
4
5// Calculations with large numbers
6console.log(9007199254740991 + 1); // correct value
7console.log(9007199254740991 + 2); // incorrect value
  • 在 JavaScript 中,數字以浮點數表示。因此,某些小數(特別是那些無法用二進制精確表示的小數)可能無法準確表達。
  • 當需要精確計算時(例如處理貨幣值),有必要避免這種四捨五入錯誤。例如,你可以使用 BigInt 或使用 toFixed() 調整小數位數。

string

1let greeting = "Hello, world!";
2let char = 'A';
3const message = `"${greeting}" in JavaScript`;
4
5console.log("Value of greeting:", greeting);
6console.log("Value of char:", char);
7console.log("Value of message:", message);
  • string是一種用於處理文本的數據類型,表示一連串字符。用單引號(')或雙引號(")括住文本來表示。自ES6起,模板字面量允許使用反引號()輕鬆嵌入變量。要嵌入變量,請使用${}`語法。

boolean

1let isAvailable = true;
2let hasError = false;
3
4console.log("Value of isAvailable:", isAvailable);
5console.log("Value of hasError:", hasError);
  • boolean表示邏輯值,只能有兩個值:truefalse。它用作條件表達式的結果或作為標誌使用。

null

1let result = null;
2
3console.log("Value of result:", result);
  • null是一種明確指示“無值”的數據類型。null由開發者設置,以指示有意的空值。

undefined

1let score;
2let subject = undefined;
3
4console.log("Value of score:", score);     // undefined
5console.log("Value of subject:", subject);
  • undefined是一種表示“未定義”的數據類型。undefined會在變量聲明但未賦值時自動分配。

bigint

1let bigIntValue = 9007199254740991n;
2let anotherBigInt = 123456789012345678901234567890n;
3
4console.log("Value of bigIntValue:", bigIntValue);
5console.log("Value of anotherBigInt:", anotherBigInt);
  • bigint 是用於處理大整數的數據類型。bigint 能夠準確表示 number 類型無法表示的大整數。bigint 字面值是通過在數字末尾添加 n 表示的。
  • bigint 是一種用於處理任意大小整數的類型,沒有範圍限制。但是,bigintnumber 無法直接一起操作,因此需要注意。

Symbol

1let sym1 = Symbol('id');
2let sym2 = Symbol('id');
3
4console.log("sym1 === sym2:", sym1 === sym2); // false
  • Symbol 是一種用於創建唯一標識符的數據類型。它可以通過 Symbol() 創建,並且可以用作對象的屬性。與其他基本類型不同,Symbol 擁有獨特的值,因此即使內容相同,它也會被視為不同的 Symbol

對象類型

對象類型是可以存儲多個值的數據結構。對象是鍵值對的集合,並且可以擁有屬性和方法。

Object

1let person = {
2    name: "John",
3    age: 30,
4    isEmployee: true
5};
6console.log(person.name); // John
  • Object 是一個包含屬性(鍵值對)的集合,可以存儲多種類型的數據。對象用花括號 {} 表示,每個屬性中鍵和值之間用 : 連接。

Array

1let numbers = [10, 20, 30];
2console.log(numbers[0]); // 10
3console.log(numbers[1]); // 20
4console.log(numbers[2]); // 30
5console.log(numbers[3]); // undefined
  • Array 是一個按順序存放多個值的列表。數組用方括號 [] 表示,值之間用逗號 , 分隔。每個元素使用從0開始的索引進行訪問。

Function

1function greet(name) {
2    return "Hello, " + name;
3}
4console.log(greet("Alice")); // Hello, Alice
  • 函數 是一種類型的對象,也是可重用的代碼塊。函數可以使用 function 關鍵字來定義。

其他對象類型

  • JavaScript 還有內置的對象類型,例如 DateRegExpMapSet。這些對象根據特定的使用情況來處理數據。

類型轉換

在 JavaScript 中,經常進行 隱式顯式類型轉換

隱式類型轉換

  • 當 JavaScript 在不同類型之間執行操作時,可能會自動轉換類型。
1let result = 5 + "5"; // "55" (the number is converted to a string)
2
3console.log(result);
  • 在這個例子中,數字 5 被隱式轉換為字串,結果是字串 "55"

顯式類型轉換

  • 開發者也可以顯式進行類型轉換。
1let num = "123";
2let convertedNum = Number(num); // Converts "123" to the number 123
3
4console.log(typeof num);
5console.log(typeof convertedNum);
  • 在這個例子中,使用了 Number() 函數將字串 "123" 明確轉換為數字 123

類型檢查

在 JavaScript 中,可以使用 typeof 運算符檢查變量的數據類型。

 1// Output: The type of 42 is: number
 2console.log('The type of 42             is:', typeof 42);
 3
 4// Output: The type of 42 is: bigint
 5console.log('The type of 42n            is:', typeof 42n);
 6
 7// Output: The type of "hello" is: string
 8console.log('The type of "hello"        is:', typeof "hello");
 9
10// Output: The type of true is: boolean
11console.log('The type of true           is:', typeof true);
12
13// Output: The type of undefined is: undefined
14console.log('The type of undefined      is:', typeof undefined);
15
16// Output: The type of null is: object
17console.log('The type of null           is:', typeof null);
18
19// Output: The type of Symbol() is: symbol
20console.log('The type of Symbol()       is:', typeof Symbol());
21
22// Output: The type of {} is: object
23console.log('The type of {}             is:', typeof {});
24
25// Output: The type of function () {} is: function
26console.log('The type of function () {} is:', typeof function () {});

結論

  • 基本類型 包括 numberstringbooleannullundefinedsymbol
  • 對象類型 包括 ObjectArrayFunction 等。
  • 由於會發生自動和顯式類型轉換,因此了解資料類型的正確使用非常重要。

您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。

YouTube Video