js - 05 JS數(shù)據(jù)類型-字符串?dāng)?shù)據(jù)類型

字符串?dāng)?shù)據(jù)類型

所有用單引號、雙引號、反引號(撇 ES6模版字符串)抱起來的都是字符串

把其他類型值轉(zhuǎn)換為字符串

  • [val].toString()
  • 字符串拼接

[val].toString()

let a = 12;
console.log(a.toString())       // => '12'
console.log((NaN).toString())   // => 'NaN'
console.log(ture.toString())    // => 'true'
console.log(false.toString())   // => 'false'
console.log(null.toString())    // => Uncaught TypeError:能用,但禁止
console.log(undefined.toString())    // => Uncaught TypeError:能用,但禁止

null/undefinned .toString() 能使用,但是會報錯,其轉(zhuǎn)換為字符串的結(jié)果就是'null'/'undefinned'
  • 普通對象({xxx:'xxx'}).toString() => '[object, Object]'
    因為:Object.prototype.toString方法不是轉(zhuǎn)換為字符串,而是用來檢測數(shù)據(jù)類型

字符串拼接

  • 在四則運算中,除加法之外,其余都是數(shù)學(xué)計算,只有加法可能會存在字符串拼接(一旦遇到字符串,則不是數(shù)學(xué)運算,而是字符串拼接)
console.log('10' + 10)      // => 1010
console.log('10' - 10)      // => 0
console.log('10px' - 10)    // => NaN

-- 計算console.log(a)
let a = 10 + null + true + [12] + undefined + 'xxx' + null + [] + 10 + false

解:10 + null => 10 + 0 => 10
    10 + true => 10 + 1 => 11
    11 + [] => 11 + '' => '11'
    '11' + undefined => '11undefined'
    ……
    解得: 
  console.log(a) => '1112undefinedxxxnull10false'
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容