所有基本類型值(Boolean、Number、String)均為「偽對象」,擁有 toString() 方法。
var b = false;
b.toString(); // "false"
默認模式:輸出十進制字符串
var n1 = 10, n2 = 10.0;
n1.toString(); // "10"
n2.toString(); // "10"
基數模式:指定進制(2-36)
var n = 10;
n.toString(2); // "1010" (二進制)
n.toString(8); // "12" (八進制)
n.toString(16); // "a" (十六進制)
var s = "blue";
s.toString(); // "blue" (返回自身)
s.length; // 4 (偽對象特性)
radix 指定進制(2-36),建議始終傳入 10 避免八進制誤判parseInt("1234blue"); // 1234
parseInt("0xA", 16); // 10
parseInt("22.5"); // 22
parseInt("blue"); // NaN
parseInt("010", 10); // 10 (關鍵:指定基數10)
parseFloat("1234blue"); // 1234
parseFloat("0xA"); // NaN (不識別十六進制)
parseFloat("22.5"); // 22.5
parseFloat("22.34.5"); // 22.34
parseFloat("0908"); // 908 (非八進制)
| 方法 | 說明 | 典型轉換結果 |
|---|---|---|
Boolean(v) |
轉布爾值 | ""、0、null、undefined、NaN → false;其餘 → true |
Number(v) |
轉數字 | "5.5"→5.5, "56"→56, "5.6.7"→NaN, true→1, false→0, null→0, undefined→NaN |
String(v) |
轉字符串 | null→"null", undefined→"undefined", true→"true", 100→"100" |
關鍵差異:String(null) 返回 "null" 不拋錯,而 null.toString() 拋錯。
引用類型即「類」的概念,操作的是對象引用。ECMAScript 通過構造函數+原型模擬類。
所有類繼承自 Object,擁有以下屬性/方法:
| 成員 | 說明 |
|---|---|
constructor |
指向創建該對象的構造函數 |
prototype |
指向對象原型(默認 Object 實例) |
hasOwnProperty(prop) |
判斷自身(非原型鏈)是否有屬性 |
isPrototypeOf(obj) |
判斷是否為某對象的原型 |
propertyIsEnumerable(prop) |
屬性是否可 for...in 枚舉 |
toString() |
返回對象字符串表示 |
valueOf() |
返回對象原始值 |
var o = new Boolean(false);
console.log(o && true); // true!所有對象在布爾上下文為 true
警告:極少直接使用 new Boolean,易產生邏輯誤解。
Number.MAX_VALUE; // 最大值
Number.MIN_VALUE; // 最小正值
Number.NaN; // 非數字
Number.POSITIVE_INFINITY;
Number.NEGATIVE_INFINITY;
var n = new Number(99);
n.valueOf(); // 99 (原始值)
n.toFixed(2); // "99.00" 固定小數位
n.toExponential(1); // "9.9e+1" 科學記數法
n.toPrecision(1); // "1e+2" 精度模式
n.toPrecision(2); // "99"
n.toPrecision(3); // "99.0"
n.toLocaleString(); // "99" (地區化,如 "99.00" 或 "99,00")
var s = new String("hello");
s.valueOf(); // "hello"
s.toString(); // "hello"
s.length; // 5
s.charAt(0); // "h"
s.concat(" world"); // "hello world"
s.indexOf("l"); // 2
s.slice(1,4); // "ell"
s.toUpperCase(); // "HELLO"
var s = "str" 而非 new String("str")Object.prototype.toString.call():
Object.prototype.toString.call([]) === '[object Array]'; // true
Object.prototype.toString.call({}) === '[object Object]'; // true
Object.prototype.toString.call(null) === '[object Null]'; // true
[] + []; // "" (空字符串)
[] + {}; // "[object Object]"
{} + []; // 0 (塊語句 + 一元加)
true + true; // 2
"5" - 2; // 3 (減法觸發 Number)
"5" + 2; // "52" (加法觸發 String)
== 的隱式轉換規則JavaScript 類型系統靈活但陷阱眾多。精通 toString/valueOf、parseInt/parseFloat 基數、強制轉換規則、包裝對象行為,是寫出健壯代碼的基石。現代開發推薦使用 TypeScript 靜態類型輔助規避低級錯誤。