此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
String() 构造函数
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
String() 构造函数创建String 对象。当作为函数调用时,它返回 String 类型的原始值。
In this article
语法
js
new String(thing)String(thing)参数
thing任何要转换为字符串的内容。
返回值
当String 作为构造函数(使用new)被调用时,它会创建一个String 对象,该对象不是原始类型。
当String 作为函数被调用时,它会将参数强制转换为一个字符串原始类型。Symbol 值会被转换成"Symbol(description)",其中description 是该 Symbol 的description 属性值,而不会抛出错误。
警告:你应该很少需要使用String 作为构造函数。
示例
>String 构造函数和 String 函数
String 函数和 String 构造函数产生不同的结果:
js
const a = new String("Hello world"); // a === "Hello world" 为 falseconst b = String("Hello world"); // b === "Hello world" 为 truea instanceof String; // 为 trueb instanceof String; // 为 falsetypeof a; // "object"typeof b; // "string"在这里,该函数生成了一个字符串(即原始值),如其所述。然而,构造函数生成了一个类型为String 的实例(即一个对象包装器),这就是为什么你很少需要使用String 作为构造函数的原因。
使用 String() 将 Symbol 转换为字符串:
String() 是唯一一种可以将 Symbol 转换为字符串而不抛出异常的方式,因为它非常明确。
js
const sym = Symbol("示例");`${sym}`; // TypeError: Cannot convert a Symbol value to a string"" + sym; // TypeError: Cannot convert a Symbol value to a string"".concat(sym); // TypeError: Cannot convert a Symbol value to a stringjs
const sym = Symbol("示例");String(sym); // "Symbol(示例)"规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-string-constructor> |
浏览器兼容性
参见
- 数字与字符串指南