萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 數據類型全解析:6 種原始類型 + Object、typeof 陷阱、弱類型特性

六大原始類型 + 一種引用類型

類型關鍵字示例typeof 結果
Numbernumber42, 3.14, NaN, Infinity"number"
Stringstring"hello", 'world', `模板`"string"
Booleanbooleantrue, false"boolean"
Nullnullnull"object" (著名 Bug)
Undefinedundefinedundefined, 未聲明變量"undefined"
Symbol (ES6)symbolSymbol('id')"symbol"
BigInt (ES2020)bigint9007199254740991n"bigint"
Objectobject{}, [], function(){}, new Date()"object" (函數為 "function")

typeof 操作符詳解

typeof "hello";        // "string"
typeof 123;            // "number"
typeof true;           // "boolean"
typeof undefined;      // "undefined"
typeof Symbol();       // "symbol"
typeof 123n;           // "bigint"
typeof null;           // "object"  (ECMAScript 歷史遺留 Bug)
typeof {};             // "object"
typeof [];             // "object"
typeof function(){};   // "function" (特殊: 函數可調用)
typeof new Date();     // "object"

判斷數組與 null 的正確姿勢

// 數組
Array.isArray([]);        // true (ES5+ 標準)
Object.prototype.toString.call([]); // "[object Array]" (通用)

// null
val === null;             // 唯一可靠方式
Object.prototype.toString.call(null); // "[object Null]"

弱類型與隱式轉換

JS 允許不同類型直接運算,引擎自動轉換:

"5" - 2;      // 3 (字符串隱式轉數字)
"5" + 2;      // "52" (數字轉字符串拼接)
true + 1;     // 2 (boolean 轉數字)
null + 1;     // 1 (null → 0)
undefined + 1; // NaN
[] + {};      // "[object Object]" (對象轉字符串)
[] + [];      // "" (空數組 → 空字符串)

嚴格相等 vs 抽象相等

null == undefined;   // true (規定相等)
null === undefined;  // false (類型不同)
0 == "";             // true
0 === "";            // false
NaN == NaN;          // false (NaN 不等於自身)
Object.is(NaN, NaN); // true (ES6 新增同值相等)

類型檢測最佳實踐封裝

function getType(val) {
    if (val === null) return 'null';
    if (typeof val !== 'object') return typeof val;
    return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
}
// 測試
getType([]);        // "array"
getType({});        // "object"
getType(null);      // "null"
getType(/re/);      // "regexp"
getType(new Date()); // "date"
copyright © 萬盛學電腦網 all rights reserved