Undefined Null Boolean String Number Symbol
Object
有空再写了~数组
这就要从 Object.prototype.toString.call(obj)提及了。
Object.prototype.toString.call(obj)能够检测传入对象obj的数据类型,可是他和经常使用的 type of 又有一些不一样。spa
JavaScript 的对象类型都继承自Object,可是每一个对象的toString会被改写。prototype
能够参考如下尝试验证过程code
let arr_0 = ['a', 1, 2] console.log(arr_0.toString()) // a,1,2 console.log(Array.prototype.hasOwnProperty('toString')) // true 这里还有toString 方法 delete Array.prototype.toString // 删除数组的toString方法 console.log(Array.prototype.hasOwnProperty('toString')) // false- 数组的toString已经被删除了 console.log(arr_0.toString()) // [object Array]
因此,不一样类型的数据在使用toString()方法的时候,会由于类在继承Object的时候改写了toString()方法,表现出不一样的结果
整理了个表格备忘对象
有兴趣的同窗能够本身试一试下面的代码blog
function getType2String(target) { return Object.prototype.toString.call(target) } console.table({ null: { val: null, typeof: typeof null, toString: getType2String(null) }, 'Symbol(s1)': { val: Symbol('s1'), typeof: typeof Symbol('s1'), toString: getType2String(Symbol('s1')) }, '[]': { val: [], typeof: typeof [], toString: getType2String([]) }, '{}': { val: {}, typeof: typeof {}, toString: getType2String({}) }, '(function(){})': { val: (function () { }), typeof: typeof (function () { }), toString: getType2String((function () { })) }, 1: { val: 1, typeof: typeof 1, toString: getType2String(1) }, ab: { val: 'ab', typeof: typeof 'ab', toString: getType2String('ab') }, true: { val: true, typeof: typeof true, toString: getType2String(true) }, Object: { val: Object, typeof: typeof Object, toString: getType2String(Object) }, 'void 0': { val: void 0, typeof: typeof void 0, toString: getType2String(void 0) }, undefined: { val: undefined, typeof: typeof undefined, toString: getType2String(undefined) },~~~~ })