1.typeof 形如 var x = "xx"; typeof x == 'string'
返回类型有:'undefined' “string” 'number' 'boolean' 'function' 'object'
缺点:对于object类型不能细分是什么类型
优点:对空null的判断 'undefined'的应用
JS 中如何判断 undefine
var exp = undefined;
if (exp == undefined) {
alert("undefined"); }
exp 为 null 时,也会得到与 undefined 相同的结果,虽然 null 和 undefined 不一样。
注意:要同时判断 undefined 和 null 时可使用本法。
var exp = undefined;
if (typeof(exp) == undefined) {
alert("undefined"); }
2.判断原型对象:
Object.getPrototypeOf(obj)==Array.prototype
问题: 只能判断直接父对象是Array.prototype的情况 无法判断间接继承Array.prototype的情况
解决: var bool=father.isPrototypeOf(child) 判断father是否是child的父级对象
不但检查直接父对象,且检查整个原型链!
3.判断构造函数:
每个原型对象都有一个constructor属性指回构造函数 obj.constructor==Array
还可以用: obj instanceof Array
要求不够严格: 只要有继承关系,就认为是数组
要求严格: 只有用数组类型创建的对象,才是真正的数组。
function A(){};
function B(){};
A.prototype = new B(); //A继承自B
var aObj = new A();
alert(aobj.constructor === B) -----------> true;
alert(aobj.constructor === A) -----------> false;
而instanceof方法不会出现该问题,对象直接继承和间接继承的都会报true
alert(aobj instanceof B) ----------------> true;
alert(aobj instanceof B) ----------------> true;
4. 检查对象的class属性
Object.prototype.toString.call(obj)
返回: "[object Class]"
对象的内部属性,专门保存创建对象时使用的类型名。
var a = "iamstring.";
var b = 222;
var c= [1,2,3];
var d = new Date();
var e = function(){alert(111);};
alert(Object.prototype.toString.call(a) === ‘[object String]’) ---> true;
alert(Object.prototype.toString.call(b) === ‘[object Number]’) ---> true;
alert(Object.prototype.toString.call(c) === ‘[object Array]’) ---> true;
alert(Object.prototype.toString.call(d) === ‘[object Date]’) ---> true;
alert(Object.prototype.toString.call(e) === ‘[object Function]’) ---> true;
alert(Object.prototype.toString.call(f) === ‘[object Function]’) ---> true;
大小写不能写错,比较麻烦,但胜在通用。
浙公网安备 33010602011771号