toString是Object原型上的一个方法所以每一个对象都有一个toString()方法。
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
1.除了null和undefined之外,其他的数据类型(数值,布尔,字符串,对象)都有toString()方法.
除了对象,对于数值,布尔,字符串,数组,函数它返回响应值的字符串表现。
因为除了Object.prototype.toString之外,其他类都对这个toString方法进行了重写。所以能直接输出字符串。
/* 这是因为toString为Object的原型方法,而Array 、Function等类型作为Object的实例,
都重写了toString方法。不同的对象类型调用toString方法时,根据原型链的知识,
调用的是对应的重写之后的toString方法(Function类型返回内容为函数体的字符串,
Array类型返回元素组成的字符串.....),
而不会去调用Object上原型toString方法(返回对象的具体类型),
所以采用obj.toString()不能得到其对象类型,
只能将obj转换为字符串类型;
因此,在想要得到对象的具体类型时,应该调用Object上原型toString方法。
*/
console.log(NaN.toString());//'NaN'
console.log(Infinity.toString());//'Infinity'
console.log((0).toString());//'0'
console.log((123).toString())//'123'
console.log(true.toString())//"true"
var foo = function() {
console.log('foo')
}
console.log(foo.toString())
/* function() {
console.log('foo')
} */
/* 对于对象,并且toString()方法在自定义对象中未被覆盖,toString() 返回 "[object type]",其中 type 是对象的类型。 */
console.log({name:'why', age: 18}.toString())//[object Object]
//toString()方法可以根据所传递的参数把数值转换为对应进制的数字字符串。参数范围为 2~36 之间的任意整数。
var a = 32;
console.log(a.toString(2)); //返回字符串100000
console.log(a.toString(4)); //返回字符串200
console.log(a.toString(16)); //返回字符串20
console.log(a.toString(30)); //返回字符串12
console.log(a.toString(32)); //返回字符串10
2.使用toString方法检测对象类型
console.log(Object.prototype.toString.call(undefined))//[object Undefined]
console.log(Object.prototype.toString.call(null))//[object Null]
console.log(Object.prototype.toString.call([1, 2, 3]))//[object Array]
//对比:console.log([1, 2, 3].toString())//1,2,3
console.log(Object.prototype.toString.call([]))//[object Array]
console.log(Object.prototype.toString.call('i am string'))//[object String]
console.log(Object.prototype.toString.call(''))//[object String]
console.log(Object.prototype.toString.call('') === '[object String]')//true
console.log(Object.prototype.toString.call(false))//[object Boolean]
console.log(Object.prototype.toString.call(false))//[object Boolean]
console.log(Object.prototype.toString.call({name:'why', age: 18}))//[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call(new Date));//[object Date]
function Person(name){this.name = name};
console.log(Object.prototype.toString.call(new Person('zhangsan')));//[object Object]
参考文章:
浅谈JS的toString:
https://www.cnblogs.com/fightjianxian/p/12342542.html
为什么用Object.prototype.toString.call(obj)检测对象类型?:
https://www.cnblogs.com/youhong/p/6209054.html
网友评论