js判断数据(数组)类型的方法

typeof --返回一个字符串,表示未经计算的操作数的类型

使用方法
typeof operand
typeof(operand)
例子
typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof null // 'object'
typeof [] // 'object'
typeof {} // 'object'
typeof console // 'object'
typeof console.log // 'function'

此处值得说一下,typeof判断null为object是一个bug,null本身不是对象,typeof不能作为判断null的方法。

同时也可以发现,引用数据类型,用typeof判断,只有function可以正确识别,其余都是object。所以typeof常用来判断基本数据类型(null除外)

instanceof() --用来判断某个元素是否某对象的构造函数实例

//使用方法
object instanceof constructor

// 定义构建函数
let Car = function() {}
let benz = new Car()
benz instanceof Car // true
let car = new String('xxx')
car instanceof String // true
let str = 'xxx'
str instanceof String // false

//可以判断数组类型
const arr = [1, 2, 3, 4]
arr instanceof Array  // true

instanceof可以准确判断复杂引用数组类型,但是不能精准判断基础数据类型。

Object.prototype.toString --通用检测数据类型

Object.prototype.toString({})       // "[object Object]"
Object.prototype.toString.call({})  // 同上结果,加上call也ok
Object.prototype.toString.call(1)    // "[object Number]"
Object.prototype.toString.call('1')  // "[object String]"
Object.prototype.toString.call(true)  // "[object Boolean]"
Object.prototype.toString.call(function(){})  // "[object Function]"
Object.prototype.toString.call(null)   //"[object Null]"
Object.prototype.toString.call(undefined) //"[object Undefined]"
Object.prototype.toString.call(/123/g)    //"[object RegExp]"
Object.prototype.toString.call(new Date()) //"[object Date]"
Object.prototype.toString.call([])       //"[object Array]"
Object.prototype.toString.call(document)  //"[object HTMLDocument]"
Object.prototype.toString.call(window)   //"[object Window]"

补充:检测数组的方法

Array.isArray() ---常用判断数组类型的方法

const arr = [1,2,3,4]
Array.isArray(arr)  
console.log(Array.isArray(arr)); // true

IE9以下版本不支持,可以用其他方式判断。

instanceof() --用来判断某个元素是否某对象的构造函数实例

同上

Object.prototype.toString --通用检测数据类型

同上

constructor --通过构造函数来判定

const arr = [1, 2, 3, 4]
arr.constructor === Array // true
arr.__proto__.constructor === Array //true

小结

Object.prototype.toString是一种比较通用的检测方法。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值