转换为字符串
- 使用 obj.toString() 方法。
var a=123;
var b=a.toString();
console.log(“a:”+typeof a+" b:"+typeof b);
- 使用 String(obj) 方法
var a=123;
var b=String(a);
console.log(“a:”+typeof a+" b:"+typeof b);
提醒:对于 null 和 undefined 两个调皮的东西,是不能用 toString()
方法的,只能使用 var obj=String(null) 。
转换为数字
- 使用Number(obj) (只能转换纯数字字符串)
var a=“123”;
var b=Number(a);
console.log(“a:”+typeof a+" b:"+typeof b);
上面是比较理想的情况,下面来一些意外。。。
- 当obj含有字符串和数字时
var a=“123abc”;
var b=Number(a);
console.log(“a:”+a+" b:"+b);
console.log(“a:”+typeof a+" b:"+typeof b);
转换结果:
- 当obj为空时
var a="";
var b=Number(a);
console.log(“a:”+a+" b:"+b);
console.log(“a:”+typeof a+" b:"+typeof b);
转换结果
- 使用parseInt(obj)
1.数字字符有序时
var a=“123abc”;
var b=parseInt(a);
console.log(“a:”+a+" b:"+b);
console.log(“a:”+typeof a+" b:"+typeof b);
2.数字字符交叉时
- var a=“1a2b3cabc”; //数字打头
var b=parseInt(a);
console.log(“a:”+a+" b:"+b);
console.log(“a:”+typeof a+" b:"+typeof b);
- var a=“a1b2c3abc”; //字母打头
var b=parseInt(a);
console.log(“a:”+a+" b:"+b);
console.log(“a:”+typeof a+" b:"+typeof b);
(无意义的转换)
转换为浮点型
- 使用parseFloat(obj)
用法同上(- .-)。
总结
小技巧
- 使用 parseInt() 浮点转整形
附加
- 其他数据类型转换为Boolean情况
使用 Boolean() 函数
- 数字 --------- > 布尔
除0和NaN外,其余都是true - 字符串 --------- > 布尔
除了空串,其余都是true - null 和 undefined 都会转换为 false