在javascript中我们一般运用typeof()
来检测变量的范例,但是在一些庞杂情况下typeof()
就显得力不从心了,下面我们来说说typeof
,constructor
和toString
,运用这三个举行范例的检测.
typeof
typeof
检测js中的基础范例照样能够的.
var num = 1;
typeof(num) // number
var str = 'hello';
typeof(str); // string
var bool = true;
typeof(bool); // boolean
关于undefined
和null
就比较特别了,
typeof(undefined); // undefined
typeof(null); // object
关于函数、数组
function a(){};
typeof(a); // function
var arr = [];
typeof(arr); // object
关于下面的检测就比较杂沓了:
typeof new Boolean(true) === 'object';
typeof new Number(1) ==== 'object';
typeof new String("abc") === 'object';
typeof new Date() === 'object';
constructor
该函数用来检察对象的组织函数
var bool = true;
console.log(bool.constructor == Boolean);// true
var num = 1;
console.log(num.constructor == Number); // true
var str = 'hello';
console.log(str.constructor == String); // true
这里须要注重的是:
关于 undefined
和 null
,不能够运用 construcor
检测.
toString
运用toString
检测,必需运用Object.prototype.toString()
,
先来看看这个东东输出什么鬼:
console.log(Object.prototype.toString()); // [object Object]
那末怎样运用toString()
来举行检测呢?这里运用 call()
来转变this
的指向,
var bool = true;
console.log(Object.prototype.toString.call(bool)); // [object Boolean]
var num = 1;
console.log(Object.prototype.toString.call(num)); // [object Number]
var str = 'hello';
console.log(Object.prototype.toString.call(str)); // [object String]
var arr = [];
console.log(Object.prototype.toString.call(arr)); // [object Array]
var a = undefined;
console.log(Object.prototype.toString.call(a)); // [object Undefined]
var b = null;
console.log(Object.prototype.toString.call(b)); // [object Null]
能够看出 运用Object.prototype.toString.call()
来检测 是比较圆满的.引荐运用.
补充 instanceof
检测某个实例是不是在某个对象的原型链上 原型链__proto__,
var c = [];
console.log(c instanceof Object); //true
var d = 123; // 这些 一般范例 并非对象
console.log(d instanceof Object); //false
var str = 'hello'; // 不是对象
console.log(str instanceof Object); //false
var num = new Number(123);
console.log(num instanceof Object);