String() 构造函数

String() 构造函数创建 String 对象。当作为函数调用时,它返回 String 类型的原始值。

¥The String() constructor creates String objects. When called as a function, it returns primitive values of type String.

语法

¥Syntax

js
new String(thing)
String(thing)

注意:String() 可以与 new 一起调用,也可以不与 new 一起调用,但效果不同。参见 返回值

¥Note: String() can be called with or without new, but with different effects. See Return value.

参数

¥Parameters

thing

任何要转换为字符串的内容。

返回值

¥Return value

String() 作为函数调用时(不带 new),它返回 value 强制转换为字符串原语。具体来说,符合 值将转换为 "Symbol(description)",其中 description 是符号的 description,而不是抛出。

¥When String() is called as a function (without new), it returns value coerced to a string primitive. Specially, Symbol values are converted to "Symbol(description)", where description is the description of the Symbol, instead of throwing.

String() 作为构造函数调用时(带有 new),它会将 value 强制转换为字符串基元(没有特殊符号处理)并返回封装 String 对象,该对象不是基元。

¥When String() is called as a constructor (with new), it coerces value to a string primitive (without special symbol handling) and returns a wrapping String object, which is not a primitive.

警告:你应该很少发现自己使用 String 作为构造函数。

¥Warning: You should rarely find yourself using String as a constructor.

示例

¥Examples

字符串构造函数和字符串函数

¥String constructor and String function

String 函数和 String 构造函数产生不同的结果:

¥String function and String constructor produce different results:

js
const a = new String("Hello world"); // a === "Hello world" is false
const b = String("Hello world"); // b === "Hello world" is true
a instanceof String; // is true
b instanceof String; // is false
typeof a; // "object"
typeof b; // "string"

在这里,该函数按照承诺生成一个字符串(primitive 类型)。但是,构造函数会生成 String 类型的实例(对象封装器),这就是你很少想使用 String 构造函数的原因。

¥Here, the function produces a string (the primitive type) as promised. However, the constructor produces an instance of the type String (an object wrapper) and that's why you rarely want to use the String constructor at all.

使用 String() 将符号字符串化

¥Using String() to stringify a symbol

String() 是唯一可以将符号转换为字符串而不抛出异常的情况,因为它非常明确。

¥String() is the only case where a symbol can be converted to a string without throwing, because it's very explicit.

js
const sym = Symbol("example");
`${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 string
js
const sym = Symbol("example");
String(sym); // "Symbol(example)"

规范

Specification
ECMAScript Language Specification
# sec-string-constructor

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also