JavaScript的数据类型,想到的是7种基本数据类型
基本类型
Undefined
Null
Boolean
String
Number
Symbol
引用类型
Object
类型说明
有空再写了~
type of 类型和 运行时类型
这就要从 Object.prototype.toString.call(obj)说起了。
Object.prototype.toString.call(obj)可以检测传入对象obj的数据类型,但是他和常用的 type of 又有一些不同。
JavaScript 的对象类型都继承自Object,但是每个对象的toString会被改写。
可以参考以下尝试验证过程
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()方法,表现出不同的结果
整理了个表格备忘
有兴趣的同学可以自己试一试下面的代码
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) },~~~~
})
发表回复