1劲藐、任意類型轉(zhuǎn)字符串
- 1锌钮、string(x)
String(1)
"1"
String(true)
"true"
String(null)
"null"
String(undefined)
"undefined"
String({})
"[object Object]"
- 2告希、x.toString()
(1).toString()
"1"
true.toString()
"true"
null.toString() //報(bào)錯(cuò)
VM125:1 Uncaught TypeError: Cannot read property 'toString' of null
at <anonymous>:1:6
(anonymous) @ VM125:1
undefined.toString() //報(bào)錯(cuò)
VM129:1 Uncaught TypeError: Cannot read property 'toString' of undefined
at <anonymous>:1:11
(anonymous) @ VM129:1
{}.toString() //報(bào)錯(cuò)
VM134:1 Uncaught SyntaxError: Unexpected token .
({}).toString()
"[object Object]"
var obj = {name:'wh'}
obj.toString()
"[object Object]" //不能變成 {name:'wh'}
注意:
1扑浸、null undefined沒(méi)有toString()屬性
2、對(duì)象的toString結(jié)果是"[object Object]"
- 3燕偶、x + ''
1+'1'
"11" //+只加相同的東西喝噪,如果不相同,嘗試去改變數(shù)據(jù)類型成相同
1+''
"1"
true+''
"true"
{}+''
0
null+''
"null"
undefined+''
"undefined"
- 4指么、window.String()
window.String(1)
"1"
window.String(null)
"null"
window.String(undefined)
"undefined"
window.String({})
"[object Object]"
window.String(true)
"true"
2酝惧、任意類型轉(zhuǎn)Boolean
Boolean(1)
true
Boolean(0)
false
Boolean('')
false
Boolean(' ')
true
Boolean(null)
false
Boolean(undefined)
false
Boolean({})
true
!!Boolean
true
注意:
1榴鼎、0,NaN,undefined,null,'',轉(zhuǎn)Boolean都為false
2、對(duì)象晚唇,函數(shù) 轉(zhuǎn)Boolean都為true巫财,不管是否為空
3 任意類型轉(zhuǎn)Number
Number('1')
1
parseInt('1',10)
1
parseFloat('1.23')
1.23
'1'-0 //減0 常用
1
+'1' //取正
1
注意:
1、parseInt(x ,進(jìn)制) 解析以數(shù)字開(kāi)頭的部分?jǐn)?shù)字字符串(非數(shù)字部分字符串在轉(zhuǎn)換過(guò)程中會(huì)被去除)哩陕。用parseInt()轉(zhuǎn)換空字符串會(huì)返回NaN平项。
parseInt('011')
11
parseInt('s')
NaN
parseInt('1s')
1
parseInt('s1')
NaN
parseInt(' ')
NaN
parseInt('1.23')
1
2、parseFloat()也可以解析以數(shù)字開(kāi)頭的部分?jǐn)?shù)字字符串(非數(shù)字部分字符串在轉(zhuǎn)換過(guò)程中會(huì)被去除)悍及。與parseInt()不同的是闽瓢,parseFloat()可以將字符串轉(zhuǎn)換成浮點(diǎn)數(shù);但同時(shí)心赶,parseFloat()只接受一個(gè)參數(shù)扣讼,且僅能處理10進(jìn)制字符串。
parseFloat("1234blue")
1234
parseFloat("0xA")
0
parseFloat("0908.5")
908.5
parseFloat("3.125e7")
31250000
parseFloat("123.45.67")
123.45
parseFloat("")
NaN
部分習(xí)題:
typeof[1,2,4]
"object"
var arr = [1,2,3]
console.log(arr[0])
1
console.log(arr['0'])
1
console.log(arr.0)
Uncaught SyntaxError: missing ) after argument list
var a = [ ]
a instanceof Array
true
var a = {0:'a', 1:'b', length: 2}
a instanceof Array
false