//1 判断是否为数组类型 var a=[0]; console.log(isArray(a)); function isArray(obj){ return (typeof obj==‘object‘) && obj.constructor==Array; } console.log("2-----------------------------------") //2 判断是否为字符串类型 console.log(isString(‘test‘)); console.log(isString(10)); function isString(str){ return (typeof str==‘string‘)&&str.constructor==String; } console.log("3-----------------------------------") //3 判断是否为数值类型 console.log(isNumber(‘test‘)); console.log(isNumber(10)); function isNumber(obj){ return (typeof obj==‘number‘)&&obj.constructor==Number; } console.log("4-----------------------------------") //4 判断是否为日期类型 console.log(isDate(new Date())); console.log(isDate(10)); function isDate(obj){ return (typeof obj==‘object‘)&&obj.constructor==Date; } console.log("5-----------------------------------") //5 判断是否为函数 console.log(isFunction(function test(){})); console.log(isFunction(10)); function isFunction(obj){ return (typeof obj==‘function‘)&&obj.constructor==Function; } console.log("6-----------------------------------") //6 判断是否为对象 console.log(isObject(new Object())); console.log(isObject(10)); function isObject(obj){ return (typeof obj==‘object‘)&&obj.constructor==Object; } /* * null 数组 日期 对象返回的是object类型 */
// js数据类型: number string boolean undefined object和函数类型 function console.log(typeof null)//object console.log(typeof Function)//function Function是包装类型 console.log(typeof undefined)//undefined var message; console.log(message)//undefined 定义了没有赋值 console.log(typeof message)//undefined 类型 console.log(null == undefined)//true /* * true==1;fase==0; * */ console.log(true == 1)//true console.log(false == 0)//true console.log(false ==2)//false var str=""; console.log(str==0);//true;空字符串将会把值转换为0 console.log(typeof str)//string var str2=new String(‘A‘); console.log(str2) //String { 0="A"}
原型扩展方法
Object.prototype.toString.call
var gettype=Object.prototype.toString gettype.call(‘aaaa‘) //[object String] gettype.call(2222) //[object Number] gettype.call(true) //[object Boolean] gettype.call(undefined) //[object Undefined] gettype.call(null) //[object Null] gettype.call({}) //[object Object] gettype.call([]) //[object Array] gettype.call(function(){}) //[object Function]
/* 其实js 里面还有好多类型判断 [object HTMLDivElement] div 对象 , [object HTMLBodyElement] body 对象 ,[object Document](IE)或者 [object HTMLDocument](firefox,google) ......各种dom节点的判断,这些东西在我们写插件的时候都会用到。*/ var gettype=Object.prototype.toString var utility={ isObj:function(o){ return gettype.call(o)=="[object Object]"; }, isArray:function(o){ return gettype.call(o)=="[object Array]"; }, isNULL:function(o){ return gettype.call(o)=="[object Null]"; }, isDocument:function(){ return gettype.call(o)=="[object Document]"|| [object HTMLDocument]; } //... }
时间: 2024-10-25 15:27:14