JavaScript中各种类型的检测

本文详细讲解了JavaScript中如何通过`typeof`运算符和`Object.prototype.toString.call()`方法检测字符串、数字、布尔、函数、undefined、null、数组、对象等类型,并区分内置和自定义对象。深入理解这些类型对于编程至关重要。
摘要由CSDN通过智能技术生成

JavaScript中各种类型的检测


// 字符串类型
typeof 'abc'  // 返回 'string'
Object.prototype.toString.call('abc') // 返回 '[object String]'

// 数字类型
typeof 123  // 返回'number'
Object.prototype.toString.call(123) // '[object Number]'

// 布尔类型
typeof true  // 返回'boolean'
Object.prototype.toString.call(true) // 返回 '[object Boolean]'

// function
typeof Object.toString // 返回'function'
Object.prototype.toString.call(Object.toString) // 返回 '[object Function]'

// undefined
typeof undefined // 返回'undefined'
Object.prototype.toString.call(undefined) // 返回 '[object Undefined]'
undefined === undefined // true

// null
typeof null  // 返回 'object'
Object.prototype.toString.call(null) // 返回 '[object Null]'
null === null // true

// 数组
function isArr(val) {
  return Array.isArray(val)
}
typeof [1, 2, 3] // 'object'
Object.prototype.toString.call([1, 2, 3]) // '[object Array]'

// 对象
function isObj(val) {
  return Object.prototype.toString.call(val) === '[object Object]'
}
typeof {a: 1, b: 'xyz'} // 'object'
Object.prototype.toString.call({a: 1, b: 'xyz'}) // '[object Object]'

// js内置的对象或自定义对象

// 内置对象
typeof new Date() // 'object'
Object.prototype.toString.call(new Date()) // '[object Date]'

// 自定义对象
class MyObj {
	constructor(name, age) {
		this.name = name
		this.age = age
	}
}
typeof new MyObj('yyy', 18) // 'object'
new MyObj('yyy', 18).constructor === MyObj // true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值