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 操作符来进行判断