我报名参加金石计划一期挑战——瓜分10万奖池,这是我的第1篇文章,[点击查看活动详情](金石计划一期 | 参与挑战 10万现金等你来瓜分! - 掘金 (juejin.cn))
1.最常见的判断方法:typeof
返回类型字符串
无法区分null 与undefined
typeof 123 ------------------>"number"
typeof "helloworld" ------------------>"string"
typeof true ------------------>"true"
typeof new Function() ------------------>"function"
typeof undefined ------------------>"undefined"
typeof 'undefined' ------------------>"string"
typeof null ------------------>"object"
typeof [1,2,3] ------------------>"object"
typeof new Date() ------------------>"object"
typeof new RegExp() ------------------>"object"
typeof Symbol() ------------------>"symbol"
2.已知对象类型: instanceof
注意:instanceof 后面一定要是对象类型,并且大小写不能错,该方法适合一些条件选择或分支。 无法区分
[1,2,3] instanceof Array -------->true
new Date() instanceof Date -------->true
new Function() instanceof Function -------->true
new Function() instanceof function -------->false
null instanceof Object -------->false
3.对象原型链判断方法: prototype 通用但很繁琐——终极判断方法
适用于所有类型的判断检测,注意区分大小写. toString方法,在Object原型上返回数据格式
var a = Object.prototype.toString;
console.log(a.call("aaa")); // [object String]
console.log(a.call(1)); // [object Number]
console.log(a.call(true)); // [object Boolean]
console.log(a.call(null)) // [object Null]
console.log(a.call(undefined)) // [object Undefined]
console.log(a.call([])) // [object Array]
console.log(a.call(function() {})) // [bject Function]
console.log(a.call({})) // [object Object]
实现判断对象的数据类型
使用 Object.prototype.toString 配合闭包,通过传入不同的判断类型来返回不同的判断函数,一行代码,简洁优雅灵活(注意传入 type 参数时首字母大写)
const isType = type => target =>`[object ${type}]` === Object.prototype.toString.call(target)
const selfIsArray = isType('Array')
Array.selfIsArray || Object.defineProperty(Array, 'selfIsArray', {
value: selfIsArray,
enumerable: false,
configurable: true,
writable: true,
})
console.log(selfIsArray([])) // true
不推荐将这个函数用来检测可能会产生包装类型的基本数据类型上,因为 call 始终会将第一个参数进行装箱操作,导致基本类型和包装类型无法区分
4.根据对象的构造器constructor进行判断
不能判断 null 和 undefined
console.log(("1").constructor === String); //true
console.log((1).constructor === Number); //true
console.log((true).constructor === Boolean); //true
console.log(([]).constructor === Array); //true
console.log((function() {}).constructor === Function); //true
console.log(({}).constructor === Object); //true
//console.log((null).constructor === Null);
//console.log((undefined).constructor === Undefined);
参考链接:js检测数据类型四种办法