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  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM