JavaScript类型判断

几种方法:typeof,instanceof,Object.prototype.toString,constructor,duck type

 

ES6引入了一种新的原始数据类型Symbol,表示独一无二的值。它是JavaScript语言的第七种数据类型,前六种是:Undefined、Null、布尔值(Boolean)、字符串(String)、数值(Number)、对象(Object)。

JavaScript5种基本类型:undefined,Number,String,null,boolean

js是一种宽松类型语言;


特殊的数值:Infinity、NaN(与自己都不相等)、Number.MAX_VALUE、Number.POSITIVE_INFINITY、

 

typeof返回值:

function,object,boolean,string,number,undefined;

对null使用typeof返回的是"object" 

 

数据类型

转化成true的值

转化成false的值

Boolean          

ture

false

String    

所有的非空字符串                

""(空字符串)

Number

任何非零数字(包括无穷大)            

0和NaN                                    

Object

任何对象

不存在

Undefined          

不存在

undefined

 确定对象类型:typeof 不是object就是类型,否则tostring()方法返回值,但这样还是不能判断自定义类;

1)typeof:

 

function isUndefined(value){return typeof value == 'undefined';}

function isDefined(value){return typeof value != 'undefined';}

function isObject(value){return value != null && typeof value == 'object';}

function isString(value){return typeof value == 'string';}

function isNumber(value){return typeof value == 'number';}

function isFunction(value){return typeof value == 'function';}

function isBoolean(value) {

  return typeof value == 'boolean';

}

 

2)toString:

 

function isDate(value){

  return toString.apply(value) == '[object Date]';

}

function isArray(value) {

  return toString.apply(value) == '[object Array]';

}

function isFile(obj) {

  return toString.apply(obj) === '[object File]';

}

 

3)(duck type)判断是否有某属性或方法:

 

function isWindow(obj) {

  return obj && obj.document && obj.location && obj.alert && obj.setInterval;

}

function isScope(obj) {

  return obj && obj.$evalAsync && obj.$watch;

}

function isElement(node) {

  return node &&

    (node.nodeName  // we are a direct element

    || (node.bind && node.find));  // we have a bind and find method part of jQuery API

}

 

instanceof  

posted @ 2016-12-14 21:43  张琼  阅读(2936)  评论(0编辑  收藏  举报