1. typeof(不能区分复杂类型)
console.log(typeof bool); //boolean
console.log(typeof num); //number
console.log(typeof str); //string
console.log(typeof und); //undefined
console.log(typeof nul); //object
console.log(typeof arr); //object
console.log(typeof obj); //object
console.log(typeof fun); //function
console.log(typeof s1); //symbol
2. instanceof(不能识别基础类型)
console.log(bool instanceof Boolean); // false
console.log(num instanceof Number); // false
console.log(str instanceof String); // false
console.log(und instanceof Object); // false
console.log(nul instanceof Object); // false
console.log(arr instanceof Array); // true
console.log(obj instanceof Object); // true
console.log(fun instanceof Function); // true
console.log(s1 instanceof Symbol); // false
3. constructor
- 有局限 => constructor可以被篡改,null、undefined没有construstor
console.log(bool.constructor === Boolean); // true
console.log(num.constructor === Number); // true
console.log(str.constructor === String); // true
console.log(arr.constructor === Array); // true
console.log(obj.constructor === Object); // true
console.log(fun.constructor === Function); // true
console.log(s1.constructor === Symbol); //true
4. Object.prototype.toString.call(全面可靠)
const isType = (value) => Object.prototype.toString.call(value).toLowerCase();
isType(null); // '[object null]'
isType(undefined); // '[object null]'
isType([]); // '[object array]'
isType({}); // '[object object]'
isType(1); // '[object number]'
isType("1"); // '[object string]'
isType(true); // '[object boolean]'
1. 希望本文能对大家有所帮助,如有错误,敬请指出
2. 原创不易,还请各位客官动动发财的小手支持一波(关注、评论、点赞、收藏)