資料型別檢測的幾種方式

2022-03-06 09:34:25 字數 1071 閱讀 1219

1.typeof

缺點:對null和array等型別的檢測不是很方便

typeof null; //"object"  

typeof ; //"object"

2.instanceof

缺點:1.只適用於物件型別

2.只要當前的這個類在例項的原型鏈上,檢測出來的結果都是true

123 instanceof number; //false  

null instanceof null; //typeerror

null instanceof object; //false

function a(){}

function b(){}

a.prototype=new b();

var aobj=new a();

aobj instanceof b;//true

aobj instanceof a;//true

3.constructor

注意:在類繼承時會出錯  

function a(){};  

function b(){};

a.prototype = new b();

var aobj = new a();

aobj.constructor === b; //true;

aobj.constructor === a; //false;

4.自定義方法實現(比較通用) 

function gettype(o)

測試:

gettype(null); //"null"  

gettype(undefined); //"undefined"

gettype(); //"array"

gettype({}); //"object"

gettype(()=>{}); //"function"

gettype(document.createelement('div')); //"htmldivelement"

JS關於資料型別檢測的幾種方式

js中我們只用乙個var就能定義所有型別的變數,非常方便,但是也同樣給我們造成了困擾,如果我們想知道乙個函式的返回值是什麼型別的,或者輸入的資訊是什麼型別的時候就要通過對資料進行檢測,所以我們該如何進行資料型別的檢測呢?資料型別檢測方式 typeof typeof 用來檢測資料型別的運算子 使用方式...

JS中檢測資料型別的幾種方式

判斷js中的資料型別有一下幾種方法 typeof instanceof constructor prototype type jquery.type 接下來主要比較一下這幾種方法的異同。var a iamstring.var b 222 var c 1 2,3 var d newdate vare ...

檢測資料型別的方式

typeof 用來檢測資料型別的運算子 首先返回的是乙個字串,其次字串中包含了對應的資料型別 number string boolean undefined function object typeof 值 值對應的資料型別 typeif 變數名 string 多次typeof後返回 string ...