js 拥有以下几种数据类型。分为基本类型和引用类型。基本类型是存在在栈中,每创建一个变量,就在栈中增加一个空间来存储变量的值,按值访问。引用类型存储在堆中,变量指向的一个堆的内存地址。
基本数据类型:
引用类型:
typeof
操作符toString
以上几种方法都可以用来判断数据类型。他们各有各的用途。
typeof
适合判断number、string、boolean、undefined。判断其他类型不准确。比如:typeof [] == Object
typeof 1
typeof '1'
typeof false
typeof undefined
toString
Object.prototype.toString.call(1) // [object Number]
Object.prototype.toString.call('1') // [object String]
Object.prototype.toString.call(false) // [object Boolean]
Object.prototype.toString.call([]) // [object Array]
Object.prototype.toString.call(null) // [object Null]
Object.prototype.toString.call(undefined) // [object Undefined]
Object.prototype.toString.call(Symbol()) // [object Symbol]
建议直接使用的tostring方法来判断数据类型。
数据类型判断函数封装。
function isNumber(number){
return Object.prototype.toString.call(number).toLowerCase() == '[object number]' ? true : false
}
function isString(string){
return Object.prototype.toString.call(string).toLowerCase() == '[object string]' ? true : false
}
function isBool(bool){
return Object.prototype.toString.call(bool).toLowerCase() == '[object boolean]' ? true : false
}
function isFunction(function){
return Object.prototype.toString.call(function).toLowerCase() == '[object function]' ? true : false
}
function isArray(array){
return Object.prototype.toString.call(array).toLowerCase() == '[object array]' ? true : false
}
function isObject(object){
return Object.prototype.toString.call(object).toLowerCase() == '[object object]' ? true : false
}
function isNull(null){
return Object.prototype.toString.call(null).toLowerCase() == '[object null]' ? true : false
}
function isUndefined(undefined){
return Object.prototype.toString.call(undefined).toLowerCase() == '[object undefined]' ? true : false
}
function isSymbol(symbol){
return Object.prototype.toString.call(symbol).toLowerCase() == '[object symbol]' ? true : false
}
function isDocument(htmldocument){
return Object.prototype.toString.call(htmldocument).toLowerCase() == '[object htmldocument]' ? true : false
}