使用Object.prototype.toString判断数据类型

var Type = {};
for ( var i = 0, type; type = [ 'String', 'Array', 'Number' ][ i++ ]; ){
  (function( type ){
    Type[ 'is' + type ] = function( obj ){
    return Object.prototype.toString.call( obj ) === '[object '+ type +']';
    }
  })( type )
};
Type.isArray( [] ); // 输出: true
Type.isString( "str" ); // 输出: true

 

 

 摘自JavaScript设计模式与开发实践

posted on 2017-02-20 15:17  传说中的页面仔  阅读(224)  评论(0编辑  收藏  举报