數(shù)據(jù)類型轉(zhuǎn)換
其他類型轉(zhuǎn)為字符串(string)
1. x.toString()
image
console.log理論上只能接受字符串:
console.log(1)將轉(zhuǎn)換成console.log( (1).toString() )
2. String(x)
image
3. 簡便方法: x + ''
image
> 1+'1'
< '11'
等價于(1).toString()+'1'
其他類型轉(zhuǎn)為數(shù)值(number)
- Number(x)
- parseInt(x,10), 10為轉(zhuǎn)為十進制,MDN詳細(xì)介紹
- parseFloat(x),MDN詳細(xì)介紹
- x - 0
- + x
方法4最常用;方法2面試題??肌?/p>
其他類型轉(zhuǎn)為布爾(Boolean)
1. Boolean(x)
2. !!x
當(dāng)轉(zhuǎn)為布爾值時,共有五個falsy值,分別為:
- o
- NaN
- ''
- null
- undefined