1、typeof
-
typeof
在对值类型number
、string
、boolean
、symbol
、undefined
、function
、bigint
的反应是精准的; -
但对于
对象{ }
、数组[ ]
、null
都会返回object
console.log(typeof ""); // string console.log(typeof 1); // number console.log(typeof NaN); // number console.log(typeof true); // boolean console.log(typeof Symbol(1)) // "symbol" console.log(typeof BigInt(11)) // "bigint" console.log(typeof undefined); // undefined console.log(typeof function(){}); // function console.log(typeof null); // object JavaScript语言设计上的一个历史遗留问题 console.log(typeof []); // object // 引用类型 console.log(typeof {}); //object // 引用类型
2、instanceof
instanceof
可以正确判断对象的类型,其内部运行机制是判断在其原型链中能否找到该类型的原型。
-
instanceof
判断一个实例是否属于某种类型 -
instanceof
运算符只能正确判断引用数据类型,而不能判断基本数据类型 -
instanceof
可以用来测试一个对象在其原型链中是否存在一个构造函数的prototype
属性// 检测构造函数B的原型是否有出现在对象A的原型链上。 A instanceof B [] instanceof Array // true [].__proto__ == Array.prototype // true
// 检测基础数据类型 console.log("1" instanceof String); // false console.log(1 instanceof Number); // false console.log(NaN instanceof Number); // false console.log(true instanceof Boolean); // false
基本类型封装成对象后才返回
true
console.log(new String("1") instanceof String); // true console.log(new Number(1) instanceof Number); // true console.log(new Number(NaN) instanceof Number); // true console.log(new Boolean(true) instanceof Boolean); // true
3、constructor
constructor 是每个实例对象都拥有的属性
constructor有两个作用:
(1)判断数据的类型;
(2)对象实例通过 constrcutor
对象访问它的构造函数(实例的constrcutor
属性,指向构造函数本身);
function Hello() {}; // 构造函数
var h = new Hello(); // 实例化对象
console.log(Hello.prototype.constructor == Hello); // true
console.log(h.constructor == Hello); // true ()
console.log(("1").constructor === String); // true
console.log((1).constructor === Number); // true
console.log((NaN).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((Symbol(1)).constructor === Symbol); // true
console.log((null).constructor === Null); // 报错
console.log((undefined).constructor === Undefined); // 报错
4、Object.prototype.toString.call()
Object.prototype.toString.call() 使用 Object 对象的原型方法toString 来判断数据类型
返回的结果结构是[object 数据类型],因此简单封装
// 定义检测数据类型的功能函数
function checkedType(target) {
return Object.prototype.toString.call(target).slice(8, -1);
}
console.log(checkedType(1)); // Number
console.log(checkedType("1")); // String
console.log(checkedType(NaN)); // Number
console.log(checkedType(true)); // Boolean
console.log(checkedType(Symbol(1))); // Symbol
console.log(checkedType(null)); // Null
console.log(checkedType(undefined)); // Undefined
console.log(checkedType([])); // Array
console.log(checkedType({})); // Object
console.log(checkedType(function () {})); // Function
5、其它补充
通过ES6的Array.isArray()
来判断数组
Array.isArrray(obj);