在 JavaScript 中,原始类型(Primitive types)本身不是对象,但它们可以像对象一样使用方法。这是因为 JavaScript 在访问原始类型的属性或方法时会自动将其"包装"为对应的对象类型。
JavaScript 有以下原始类型:
原始类型 | 对应的对象类型 | 示例 |
---|---|---|
string |
String |
"hello" |
number |
Number |
123 , 3.14 |
boolean |
Boolean |
true , false |
symbol |
Symbol |
Symbol("desc") |
bigint |
BigInt |
123n |
null |
无 | null |
undefined |
无 | undefined |
当你尝试访问原始值的属性或方法时,JavaScript 会:
这个过程是自动且透明的。
let str = "Hello";
console.log(str.toUpperCase()); // "HELLO"
console.log(str.toLowerCase()); // "hello"
console.log(str.charAt(1)); // "e"
console.log(str.indexOf("l")); // 2
console.log(str.includes("ell")); // true
console.log(str.slice(1, 3)); // "el"
console.log(str.substring(1, 3)); // "el"
console.log(str.replace("l", "L")); // "HeLlo"
console.log(str.split("")); // ["H", "e", "l", "l", "o"]
console.log(" hello ".trim()); // "hello"
let num = 123.456;
console.log(num.toFixed(2)); // "123.46"
console.log(num.toPrecision(5)); // "123.46"
console.log(num.toString()); // "123.456"
console.log(num.toString(2)); // 二进制表示
console.log((123).toString()); // 注意字面量需要括号
let bool = true;
console.log(bool.toString()); // "true"
console.log(bool.valueOf()); // true
let sym = Symbol("description");
console.log(sym.toString()); // "Symbol(description)"
console.log(sym.description); // "description"
原始类型不是对象:尽管可以使用方法,但原始值本身不是对象。
let str = "hello";
console.log(typeof str); // "string"
str.test = "value"; // 临时对象被创建后立即销毁
console.log(str.test); // undefined
构造函数与原始值:
let strObj = new String("hello"); // 创建一个String对象
console.log(typeof strObj); // "object"
null 和 undefined:这两个原始类型没有对应的包装对象,也没有可用的方法。
let x = null;
x.toString(); // TypeError
性能考虑:虽然 JavaScript 引擎会优化包装过程,但过度使用原始类型方法可能影响性能。
理解原始类型的方法机制有助于更好地使用 JavaScript 并避免常见的陷阱。