1、任意类型转字符串
- 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() //报错
VM125:1 Uncaught TypeError: Cannot read property 'toString' of null
at <anonymous>:1:6
(anonymous) @ VM125:1
undefined.toString() //报错
VM129:1 Uncaught TypeError: Cannot read property 'toString' of undefined
at <anonymous>:1:11
(anonymous) @ VM129:1
{}.toString() //报错
VM134:1 Uncaught SyntaxError: Unexpected token .
({}).toString()
"[object Object]"
var obj = {name:'wh'}
obj.toString()
"[object Object]" //不能变成 {name:'wh'}
注意:
1、null undefined没有toString()属性
2、对象的toString结果是"[object Object]"
- 3、x + ''
1+'1'
"11" //+只加相同的东西,如果不相同,尝试去改变数据类型成相同
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、任意类型转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,'',转Boolean都为false
2、对象,函数 转Boolean都为true,不管是否为空
3 任意类型转Number
Number('1')
1
parseInt('1',10)
1
parseFloat('1.23')
1.23
'1'-0 //减0 常用
1
+'1' //取正
1
注意:
1、parseInt(x ,进制) 解析以数字开头的部分数字字符串(非数字部分字符串在转换过程中会被去除)。用parseInt()转换空字符串会返回NaN。
parseInt('011')
11
parseInt('s')
NaN
parseInt('1s')
1
parseInt('s1')
NaN
parseInt(' ')
NaN
parseInt('1.23')
1
2、parseFloat()也可以解析以数字开头的部分数字字符串(非数字部分字符串在转换过程中会被去除)。与parseInt()不同的是,parseFloat()可以将字符串转换成浮点数;但同时,parseFloat()只接受一个参数,且仅能处理10进制字符串。
parseFloat("1234blue")
1234
parseFloat("0xA")
0
parseFloat("0908.5")
908.5
parseFloat("3.125e7")
31250000
parseFloat("123.45.67")
123.45
parseFloat("")
NaN
部分习题:
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