前端效验数据类型有很多种,但是有些方法是并不能很好并且准确的检测出是什么类型的,以下是我个人的总结,和优缺点

第一种:typeof(返回相应的数据类型)

typeof false // "boolean"
typeof 'aaa' // "string"
typeof 123 // "number"
typeof {} // "object"
typeof [] // "object"
typeof null // "object"
typeof function(){} // "function"

这种方法不难看出,当数据类型为引用类型时,检测出返回的是object类型,其中对于null检测出也是object,熟悉原型链的就知道,最终指向的其实就是null,所以这种方法个人认为适合检测基本数据类型

第二种:instanceof(返回布尔值,判断是还是不是)

"aaa" instanceof String // false
new String("aaa") instanceof String // true
new Date() instanceof Date // true
({}) instanceof Object // true
[] instanceof Array // true
[] instanceof Object // true

这个相对于上面一种是比较好一点的,但是还是存在偏差,不够准确,比如 Array 和 Object 都出现在 [] 的原型链上,可能会将 [] 误认为 Object 类型

第三种:toString.call()(返回的也是对应得类型)

toString.call(undefined) // "[object Undefined]"
toString.call(false) // "[object Boolean]"
toString.call('aaa') // "[object String]"
toString.call(123) // "[object Number]"
toString.call({}) // "[object Object]"
toString.call([]) // "[object Array]"
toString.call(null) // "[object Null]"
toString.call(function(){}) // "[object Function]"

这种方法就比较完善准确了,也是工作中常用到得检测手法,比较靠谱

第四种:constructor (返回布尔值)

const flg = true;flg.constructor === Boolean // true
const aaa = 'aaa';aaa.constructor === String // true
const num = 123;num.constructor === Number // true
const obj = {};obj.constructor === Object // true
const arr = [];arr.constructor === Array // true
const fun = function(){};fun.constructor === Function // true

这种方法相对于第一种和第二种其实还是没啥问题得,但是有个弊端就是constructor 所指向的的构造函数是可以被修改的,当然一般只要不主动去修改所指向得构造函数那么也不会有啥太大问题

第五种:lodash插件
这种就是第三方封装好得插件了,用起来比较方便,lodash提供了很多实用的方法,比如两个数组比较差异,比如对象中查找指定的某个元素,相比原生的方法来说更方便点,并且兼容了一些偏差性问题,lodash只种也是有效验数据类型的方法的
例如:

_.isNumber(3);
// => true
_.isNumber(Number.MIN_VALUE);
// => true
_.isNumber(Infinity);
// => true
_.isNumber('3');
// => false


_.isNull(null);
// => true
_.isNull(void 0);
// => false


_.isObject({});
// => true
_.isObject([1, 2, 3]);
// => true
_.isObject(_.noop);
// => true
_.isObject(null);
// => false


_.isString('abc');
// => true
_.isString(1);
// => false

我列举了几种,类似于这种的还有很多以下是文档地址,可以了解下lodash文档

工作中一般用lodash的,或者是自己封装的比较多,以下自己封装的仅供参考学习

const isUndefined = value => typeof value === 'undefined'

const isNull = value => Object.prototype.toString.call(value) === '[object Null]'

const isNumber = value => Object.prototype.toString.call(value) === '[object Number]'

const isString = value => Object.prototype.toString.call(value) === '[object String]'

const isFunction = value => Object.prototype.toString.call(value) === '[object Function]'

const isArray = value => Object.prototype.toString.call(value) === '[object Array]'

const isArrayEmpty = value => isArray(value) && value.length === 0

const isObject = value => Object.prototype.toString.call(value) === '[object Object]'

const isObjectEmpty = value => isObject(value) && Object.keys(value).length === 0

以上就是个人简单的叙述下啦,希望对各位有点帮助,有问题请私发我,谢谢