語法
js
new String(thing)
String(thing)
引數
thing-
要轉換為字串的任何內容。
返回值
當 String() 作為函式呼叫時(不帶 new),它會返回 被強制轉換為字串原始值 的 value。特別地,Symbol 值會被轉換為 "Symbol(description)",其中 description 是 Symbol 的 描述,而不是丟擲錯誤。
當 String() 作為建構函式呼叫時(帶 new),它會將 value 強制轉換為字串原始值(不進行特殊的符號處理),並返回一個包裝的 String 物件,該物件不是原始值。
警告: 你很少會發現自己需要使用 String 作為建構函式。
示例
String 建構函式與 String 函式
String 函式和 String 建構函式產生不同的結果
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"
在這裡,函式如預期地產生了一個字串(原始型別)。然而,建構函式產生的是 String 型別的一個例項(一個物件包裝器),這就是為什麼你通常不希望使用 String 建構函式的原因。
使用 String() 將符號轉換為字串
String() 是唯一一種可以將符號轉換為字串而不會丟擲錯誤的情況,因為它非常明確。
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)"
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-string-constructor |
瀏覽器相容性
載入中…
另見
- 數字和字串指南