字符串是不可變的。函數
每一個字符是一個16
位的UTF-16
編碼單元,這意味着一個Unicode
字符至關於一個或兩個JavaScript
字符。編碼
即用單引號或雙引號括起來的字符序列。spa
'string text' "string text" "中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어"
new String(thing)
由String()
構造函數獲得字符串對象prototype
> var s = new String(123) > typeof s 'object' >
區分二者很簡單。code
字符串字面量 以及 String()
函數做爲普通函數調用時的返回值,這兩種狀況下獲得的是字符串原始值。對象
判斷字符串原始值方法爲typeof 'xxx'
,獲得‘string’
,即ip
> typeof 'ad' 'string' // 字符串原始值
由new String()
構造器函數獲得的是字符串對象。字符串
判斷字符串對象的方法也爲typeof 'xxx'
, 獲得‘object’
,即string
> var s = new String(123) > typeof s 'object' // 字符串對象 >
最重要一點,字符串原始值也能夠調用字符串對象所具備的方法,由於JavaScript
內部會自動將字符串原始值轉化爲字符串對象,以調用相關方法,而後恢復。it
function isString (value) { return Object.prototype.toString.call(value) === '[object String]'; }
function isStringPrimitive (value) { return typeof value === 'string'; }
function isString (value) { return Object.prototype.toString.call(value) === '[object String]' && typeof value === 'object'; }