解惑toString()

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值