序:歌谷浏览器中,字符串显示为黑色,数值类型是蓝色,布尔类型也是蓝色,undefined和null是灰色的。
1.toString()
常规使用
var num = 123
var res1 = num.toString();
console.log(res1); //123
console.log(typeof res1); //string
var num1 = false;
var res2 = num1.toString();
console.log(res2); //false
console.log(typeof res2); //string
该方法不会改变原变量,只会返回生成后的值;可以携带一个参数,输出对应进制的值。
var num2 = 'fengjing';
console.log(num2.toString(2)); //fengjing
console.log(num2.toString(10)); //fengjing
var num3 = 100;
console.log(num3.toString(2)); //1100100
console.log(num3.toString(8)); //144
2.null
和undefined
没有toString
方法,调用则报错,以为它俩会直接转换成字符串。
var n1 = null;
var s1 = String(n1);
var n2 = undefined;
var s2 = String(n2);
console.log(n1); //null
console.log(typeof n1); //object
console.log(s1); //null
console.log(typeof s1); //string
console.log(n2); //undefined
console.log(typeof n2); //undefined
console.log(s2); //undefined
console.log(typeof s2); //string
3.对于Number和Boolean,String相当于调用toString方法。
var n1 = 100;
console.log(String(n1)); //100
console.log(typeof String(n1)); //string
var b1 = true;
console.log(String(b1)); //true
4.拼接字符串方式:任何数据+""
都会转换成字符串,内部实现原理和String()是一样的,强制转换。
var num7 = 100;
var s4 = num7 + "";
console.log(s4); //100
console.log(typeof s4); //string
var s5 = null;
var s6 = s5 + '';
console.log(s6); //null
console.log(typeof s6); //string
var s7 = undefined;
var s8 = s7 + "";
console.log(s8); //undefined
console.log(typeof s8); //string
var s9 = true;
var s10 = s9 + '';
console.log(s10); //true
console.log(typeof s10); //string