js实现类型
JavaScript 类型判断方法
JavaScript 提供了多种方式来判断变量的类型,以下是常见的几种方法:
typeof 操作符
typeof 'hello' // 'string'
typeof 42 // 'number'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof null // 'object' (历史遗留问题)
typeof function() {} // 'function'
typeof [] // 'object'
typeof {} // 'object'
instanceof 操作符 用于检测构造函数的 prototype 属性是否出现在对象的原型链中:
[] instanceof Array // true
new Date() instanceof Date // true
{} instanceof Object // true
Object.prototype.toString.call() 更精确的类型判断方法:
Object.prototype.toString.call('hello') // '[object String]'
Object.prototype.toString.call(42) // '[object Number]'
Object.prototype.toString.call(true) // '[object Boolean]'
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call(undefined) // '[object Undefined]'
Object.prototype.toString.call([]) // '[object Array]'
Object.prototype.toString.call({}) // '[object Object]'
Object.prototype.toString.call(function() {}) // '[object Function]'
Array.isArray() 专门用于判断数组类型:

Array.isArray([]) // true
Array.isArray({}) // false
自定义类型判断函数 可以封装一个通用的类型判断函数:
function getType(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}
getType('hello') // 'string'
getType([]) // 'array'
getType(null) // 'null'
类型转换方法
显式类型转换
Number('123') // 123
String(123) // '123'
Boolean(1) // true
隐式类型转换

'5' + 1 // '51' (字符串拼接)
'5' - 1 // 4 (数字运算)
'5' * '2' // 10
!0 // true
特殊类型检查
检查 NaN
isNaN(NaN) // true
isNaN('hello') // true
Number.isNaN(NaN) // true (ES6更精确的方法)
Number.isNaN('hello') // false
检查有限数字
isFinite(Infinity) // false
isFinite(42) // true
Number.isFinite(42) // true (ES6方法)
检查整数
Number.isInteger(42) // true
Number.isInteger(42.0) // true
Number.isInteger(42.1) // false
这些方法组合使用可以覆盖JavaScript中大部分类型判断和转换的需求。根据具体场景选择合适的方法,特别是要注意typeof null返回'object'这种特殊情况。






