-
7种简单的基本类型
string、number、boolean、null、undefined、object、symbol
-
引用类型 (对象的子类型)
String、Number、Boolean、Object、Function、Array、Date、RegExp、Error
1. typeof()返回值只有六种类型:string、number、boolean、undefined、object、function
— 对于引用类型,除了返回 “function”
,其他都是 “object”
typeof(null) 会返回“object”
—— 此为Javascript历史遗留bug
typeof(未定义的变量 || undefined ) 都会返回 “undefined”
typeof(function(){}) 会返回 “function”
2. Object.prototype.toString.call()通常用来判断数据的类型
console.log(Object.prototype.toString.call("")) // "[object String]"
console.log(Object.prototype.toString.call(1)) // "[object Number]"
console.log(Object.prototype.toString.call(true)) //"[object Bolean]"
console.log(Object.prototype.toString.call(null)) //"[object Null]"
console.log(Object.prototype.toString.call(undefined)) // "[object Undefined]"
console.log(Object.prototype.toString.call(a)) // 会报ReferenceError
console.log(Object.prototype.toString.call({})) // "[object Object]"
console.log(Object.prototype.toString.call([])) // "[object Array]"
console.log(Object.prototype.toString.call(function(){})) //"[object Function]"
console.log(Object.prototype.toString.call(new Error())) // "[object Error]"
console.log(Object.prototype.toString.call(/$1/)) // "[object RegExp]"
console.log(Object.prototype.toString.call(new Date())) // "[object Date]"
二者区别:
var str ="hello world";
var newStr = new String(str); // 通过构造函数创建了一个实例对象
console.log(typeof(str)) // "string"
console.log(typeof(newStr)) // "object"
console.log(Object.prototype.toString.call(str)) // "[object String]"
console.log(Object.prototype.toString.call(newStr)) // "[object String]"
题外话:标识符str是一个普通的字面量,如果想要在字面量上进行一些操作。比如获取长度,访问某个字符等,需要先转化为String对象
。然而JS引擎会自动帮你把字符串字面量转化为一个String对象
,并不需要你显式的创建一个对象,就可以直接在字面量上访问属性或者方法。(数值字面量和布尔字面量同理,会自动转化为Number对象
和Boolean对象
)