解惑toString()

2,332 阅读1分钟

toString() 函数返回一个表示该对象的字符串

数值

console.log((4).toString())  // '4'

字符串

console.log('nwd'.toString())  // 'nwd'

布尔

console.log(true.toString()) // 'true'

对象 非数组

console.log({}.toString())  // [object Object]


对象数组

console.log([4,6].toString()) // 4,6

null

console.log(null.toString())  // Uncaught TypeError: Cannot read property 'toString' of null


undefined

console.log(undefined.toString())  // Uncaught TypeError: Cannot read property 'toString' of undefined

toString 方法到底定义在何处?

console.log(Object.prototype.toString)
//ƒ toString() { [native code] }


 Object.prototype.toString.call(value)

判断基本类型

        
        console.log(Object.prototype.toString.call(null))// [object Null]

	console.log(Object.prototype.toString.call(undefined));//[object Undefined]

	console.log(Object.prototype.toString.call("nwd"));//[object String]

	console.log(Object.prototype.toString.call(2));//[object Number]

	console.log(Object.prototype.toString.call(true));//[object Boolean]

判断函数

        function fn() {}

	console.log(Object.prototype.toString.call(fn)) //[object Function]

判断日期类型

        var date = new Date();

	console.log(Object.prototype.toString.call(date)); //[object Date]

判断正则

        var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
	/*这个表达式的意思是:
	1--以1为开头;

	2--第二位可为3,4,5,7,8,中的任意一位;

	3--最后以0-9的9个整数结尾。*/
	console.log(Object.prototype.toString.call(myreg)); // [object RegExp]

判断自定义类型

        function Person() {

	}
	var p1 = new Person()
	console.log(Object.prototype.toString.call(p1)) //[object Object]
	console.log(Object.prototype.toString.call([3,7])) //[object Object]
	console.log(p1 instanceof Person); // true 

注:很明显这种方法不能准确判断person是Person类的实例,而只能用instanceof 操作符来进行判断