码迷,mamicode.com
首页 > 编程语言 > 详细

JS数组类型检测

时间:2016-04-04 06:48:00      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

在强类型语言,数组类型检测是非常容易的事情(typeof就可以解决),而在弱语言JS数据类型就很容易混淆了。

JS中常见的数据类型有:number、string、boolean、undefined、function、array、Object和null。下面先用typeof来测试下:

var k = 9;
console.log(typeof k);  //number

检测number可以用typeof来检测了。

var k = "string";
console.log(typeof k);  //string

检测string可以用typeof来检测了。

var k = true;
console.log(typeof k);   //Boolean

检测boolean可以用typeof来检测了。

var u;
console.log(typeof u);  //undefined

检测undefined也可以用typeof来检测。

var f = function(){};
console.log(typeof f);   //function

function 也可以用typeof来检测。

var t = null;
console.log(typeof t);   //object
var array = [];
console.log(typeof array); //object
var obj = {};
console.log(typeof obj);    //object

用typeof来检测null,array和object检测的都是object。看来需要对这三种数据结构进行特殊处理。

function type(o){
     return (o === null) ? "null": (typeof o)  
}

先对null进行特殊处理,在看看array和object有没有其它属性来判断。

var array = [];
var toString = Object.prototype.toString;
console.log(toString.apply(array)); //[object Array]

var obj = {}; 
console.log(toString.apply(obj));//[object Object]

OK,通过检测其它数据类型:regexp和date也可以通过这种方式来检测:

var regex = /^\s+/; 
var toString = Object.prototype.toString;
console.log(toString.apply(regex));  //[object RegExp]
var date = new Date(); 
console.log(toString.apply(date));  //[object Date]

最后,我们来写一个通用的函数来对JS数据类型检测:

function typeOf(e){
    var _toString = Object.prototype.toString;
    var _type = {
        "undefined":"undefined",
        "number":"number",
        "boolean":"boolean",
        "string":"string",
        "function":"function",
        "[object RegExp]":"regex",
        "[object Array]":"array",
        "[object Date]":"date"
    }
    return _type[typeof  e] || _type[_toString.call(e)] ||(e? "object":"null");
}

我在zepto.js中看到另外一些检测数据类型的方式,可以参考:

var toString = ({}).toString;           //挺巧妙的。
 function isFunction(value) { 
    return toString.call(value) == "[object Function]" 
}
function isObject(value) { 
    return value instanceof Object 
}
//对于通过字面量定义的对象和new Object的对象返回true,new Object时传参数的返回false
//new Object时传参数的构造函数的原型链没有isPrototypeOf属性,而构造函数的原型链的__proto__对象有。
function isPlainObject(value) {
    var key, ctor
    //如果不是object类型返回。
    if (toString.call(value) !== "[object Object]") return false 
    //获得该对象原型链中的属性或者对象 
    ctor = (isFunction(value.constructor) && value.constructor.prototype)
    //该原型链中没有对象或者属性 或者有但是不属性不存在isPrototypeOf,返回为false 
    if (!ctor || !hasOwnProperty.call(ctor, ‘isPrototypeOf‘)) return false
    for (key in value);
    return key === undefined || hasOwnProperty.call(value, key)
}
function isArray(value) { 
    return value instanceof Array 
}
function likeArray(obj) {     //类数组,不是真正的数组,是对象,有一个成员类型“length”
    return typeof obj.length == ‘number‘ 
}

 

JS数组类型检测

标签:

原文地址:http://www.cnblogs.com/liuyinlei/p/5351327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!