DEV Community

SGsSY
SGsSY

Posted on

The Most Familiar Stranger - JavaScripts - 型別

分享記錄檔 YouTube

原始型別

在 JavaScript 中,原始型別 (primitive type) 是指不可變 (immutable) 且沒有任何方法 (method) 的資料型別,共有 7 種原始型別,包括:

  1. number:代表數字,包括整數和浮點數。
  2. string:代表字串,用引號 (single quotes 或 double quotes) 包括起來。
  3. boolean:代表布林值,只有兩個值 true 和 false。
  4. null:代表空值,只有一個值 null。
  5. undefined:代表未定義的值,只有一個值 undefined。
  6. symbol:代表唯一的識別符號,是 ES6 引入的新型別。
  7. BigInt:代表數字,可以精確地表示大於 number 最大值 ( 2 的 53 次方 ) 的數字。

💡 JS 的原始型別是沒有方法的,因為原始型別的值不可變,調用方法需要在物件上執行操作,而不是值,所以不能直接在原始型別上調用方法。當我們在一些原始型別上調用方法時,JS 會暫時轉為包裹器物件 (Wrapper Object),完成操作後再轉回原始型別。

以下是一些使用原始型別的範例:

let num = 123; // number
let str = 'Hello, world!'; // string
let bool = true; // boolean
let n = null; // null
let u = undefined; // undefined
let sym = Symbol('foo'); // symbol
Enter fullscreen mode Exit fullscreen mode

原始型別在 JavaScript 中非常常用,因為它們是非常基本的資料型別,且在程式執行時具有很高的效能。

型別轉換

有時我們會依需求主動進行變數的型別轉換,例如:

let numStr = '123';
let num = parseInt(numStr); // 將字串轉換為整數
console.log(num); // 123

let bool = true;
let num2 = +bool; // 將布林值轉換為數字
console.log(num2); // 1

let str = 'Hello, world!';
let bool2 = Boolean(str); // 將字串轉換為布林值
console.log(bool2); // true
Enter fullscreen mode Exit fullscreen mode

但在執行一些運算式時,JavaScript 會自動進行型別轉換,這種轉換被稱為隱式轉換 ( implicit coercion ) 或強制轉換 ( type coercion )。

10 + ' Hi';      // '10 Hi'
'7' * '4';       // 28
let n = 1 - 'x'  // n = NaN
Enter fullscreen mode Exit fullscreen mode
轉為字串 轉為數字 轉為 Boolean
undefined ‘undefined’ NaN false
null ‘null’ 0 false
true ‘true’ 1
false ‘false’ 0
‘’ 0 false
‘1.2’ 1.2 true
‘one’ NaN true
0 ‘0’ false
-0 ‘0’ false
1 ‘1’ true
Infinity ‘Infinity’ true
-Infinity ‘Infinity’ true
NaN ‘NaN’ false
{} toString() valueOf() true
[] ‘’ 0 true
[9] ‘9’ 9 true
[’a’] join() NaN true
function(){} toString() NaN true

型別比較

JS 會將型別轉為數字 ( valueOf() ) 或字串 ( toString() ) 然後進行比較,假如轉數字不行會嘗試轉字串,反之轉字串不行會嘗試轉數字。

💡 Date 型別會優先轉字串,其餘會優先轉數字

Number([9]);
// => Number('9'),因為 Array 類別的 valueOf() 不會回傳原始值,所以改為嘗試 toString()
// => 9
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up