JavaScript型別檢測

2021-07-05 13:14:43 字數 759 閱讀 8289

型別檢測方法如下:typeof,instanceof,object.prototype.tostring,constructor,duck type.

1.部分示例如下:

typeof 100   :   "number";

typeof true  :    "boolean";

typeof function   :  "function";

typeof(undefined)   :「undefined」;

typeof new object()   : "object";

typeof [1,2]   : "object";

typeof nan  : "number";

typeof null   : "object";

注意:typeof null === "object";

2.  obj instanceof object

示例:[1,2] instanceof array === true;

new object() instance array === false;

型別檢測小結:

(1)適合基本型別及function檢測,遇到null失效;

(2)[[class]]:  通過{}.tostring拿到,適合內建物件和基元型別,遇到null和undefined失效(ie678返回[object object]).

(3)instanceof:適合自定義物件,也可以用來檢測原生物件,在不同iframe和window間檢測時失效。

javascript 型別檢測

1 檢測字串 數值 布林值 undefined function 使用typeof 在safari和chrome中檢測正則也會返回 function 2 檢測null 應用 3 檢測其它物件 方法一 利用instanceof constructor 再某些ie版本中存在跨iframe問題,每個ifr...

JavaScript檢測型別

es有五種簡單的資料型別 undefined,null,boolean,number和string,還有一種複雜的資料型別object。對乙個值使用typeof操作符可能返回下列某些字串 undefined 如果這個值未定義 boolean 如果這個值是布林值 string 如果這個值是字串 num...

JavaScript 型別檢測

返回乙個字串,來表示資料的型別 typeof 運算子用來檢測建構函式是否存在與檢測物件的原型鏈上,返回布林 instanceof 精確判斷物件的型別,使用call指向 this 檢測物件,string和array構造重寫了tostring 方法 object.prototype.tostring.c...