伪对象
即便是基本类型,也是伪对象,所以他们都有属性和方法。
变量a的类型是字符串,通过调用其为伪对象的属性length获取其长度
var a='Hello';
document.write('变量a的长度是'+a.length)
转换字符串
无论是Number,Boolean还是String都有一个toString方法,用于转换为字符串
var a=10;
var b=true;
var c='hello javascript';
document.write(a.toString()+"<br/>");
document.write(b.toString()+"<br/>");
document.write(c.toString()+"<br/>");
数字转换为字符串
Number转换为字符串的时候有默认模式和基模式两种
var a=10;
document.write('默认模式下,数字10转换为十进制'+a.toString());//默认模式,即十进制
document.write("<br>");
document.write('基模式下,数字10转换为二进制的'+a.toString(2));//基模式,二进制
document.write("<br>");
document.write("基模式下,数字10转换为八进制的"+a.toString(8));//基进制,八进制
document.write("<br>");
document.write("基模式下,数字10转换为十六进制的"+a.toString(16));//基模式,十六进制
document.write("<br>");
转换为数字
javascript分别提供内置函数 parseInt()和parseFloat(),转换为数字
document.write(parseFloat("666666"));
document.write(parseInt("10abc8"));
转换为Boolean
使用内置函数Boolean() 转换为Boolean值
当转换字符串时:
非空即为true
当转换数字时:
非0即为true
当转换对象时:
非null即为true
document.write("空字符串''转换为布尔值后的值"+Boolean(""));//空字符串
document.write("<br>");
document.write("非空字符串转换为布尔后的值"+Boolean("hello javascript"));
document.write("<br>");
document.write("数字0转换为布尔值后的值"+Boolean(0));//0
document.write("<br>");
document.write("数字3.14转换为布尔后的值"+Boolean(3.14));//非0
document.write("<br>");
document.write("空对象null转换为布尔后的值"+Boolean(null));//null
document.write("<br>");
document.write("非空对象 new Object()转换布尔后的值:"+Boolean(new Object()));//对象存在
document.write("<br>");
结果:
空字符串''转换为布尔值后的值false
非空字符串转换为布尔后的值true
数字0转换为布尔值后的值false
数字3.14转换为布尔后的值true
空对象null转换为布尔后的值false
非空对象 new Object()转换布尔后的值:true
Number()和parseInt()的区别
Number()和parseInt()一样,都可以用来进行数字的转换
区别在于,当转换的内容包含非数字的时候,Number() 会返回NaN(Not a Number)
parseInt() 要看情况,如果以数字开头,就会返回开头的合法数字部分,如果以非数字开头,则返回NaN
String()和toString()的区别
String()和toString()一样都会返回字符串,区别在于对null的处理
String()会返回字符串"null"
toString() 就会报错,无法执行
var a=null;
document.write('String(null)把空对象转换为字符串'+String(a));
document.write('null.toString()就会报错'+a.toString());