js中typeof與instanceof用法小記

2021-09-06 22:42:19 字數 809 閱讀 1624

今天寫js**,遇到動態生成多個名稱相同的input複選按鈕

需要判斷其是否是陣列,用到了if (typeof(document.mapcheckmgr.checkid)!="undefined")

以前用得少,就順便查了一下關於typeof的那些事

typeof用以獲取乙個變數或者表示式的型別,typeof一般只能返回如下幾個結果:

number,boolean,string,function(函式),object(null,陣列,物件),undefined。

如:alert(typeof (123));//typeof(123)返回"number" 

alert(typeof ("123"));//typeof("123")返回"string"

我們可以使用typeof來獲取乙個變數是否存在,如if(typeof a!="undefined"){},而不要去使用if(a)因為如果a不存在(未宣告)則會出錯,

正因為typeof遇到null,陣列,物件時都會返回object型別,所以當我們要判斷乙個物件是否是陣列時

或者判斷某個變數是否是某個物件的例項則要選擇使用另乙個關鍵語法instanceof

instanceof用於判斷乙個變數是否某個物件的例項,如var a=new array();alert(a instanceof array);會返回true,

同時alert(a instanceof object)也會返回true;這是因為array是object的子類。

再如:function test(){};var a=new test();alert(a instanceof test)會返回true。

js中typeof與instanceof的區別

最近在看 高程 三 看到書中一些例子,就想到typeof和instanceof的區別。眾所周知,js資料型別可分為基本資料型別和引用資料型別 基本型別是儲存在棧記憶體中的簡單資料段,簡言之也就是有單一字面量的值 引用資料型別指的是有多個值構成的物件。那麼typeof與instanceof的區別到底有...

js中typeof 與instanceof的區別

用來檢測給定變數的資料型別,其返回的值是下列某個字串 undefined 變數未定義 boolean 變數為布林型別 string 變數為字串 number 變數為數值 object 變數為物件或null function 變數為函式 alert typeof null 返回 object 特殊值n...

js中typeof與instanceof用法小記

今天寫js 遇到動態生成多個名稱相同的input複選按鈕 需要判斷其是否是陣列,用到了if typeof document.mapcheckmgr.checkid undefined 以前用得少,就順便查了一下關於typeof的那些事 typeof用以獲取乙個變數或者表示式的型別,typeof一般只...