JS中对象类型的检测

2016-08-30  本文已影响0人  无法找到此用户

检测一个对象是否存在:

if (typeof myObj === 'undefined') {
    var myObj = {};
}

可用于检测对象类型的运算符:

function isArray (arr) {
    return arr instanceof Array;
}

也可以通过

function isArray (arr) {
    return typeof arr === 'object' && arr.constructor === Array;
}

但是instanceof在某些IE版本中无效,且同一个页面中的不同框架(ifame)不共享prototype,所以最佳实践是:

if (typeof Array.isArray === 'undefined') {
     Array.isArray = function (arr) {
        return Object.prototpe.toString.call(arr) === '[object Array]'
    } 
}

一个用于获取对象类型名的通用函数:

function __getClass (object) {
    return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]&/)[1];
}

通过拓展,可以编写一个检测的函数:

function is (type, object) {
    return type === __getClass(object);
}
上一篇 下一篇

猜你喜欢

热点阅读