js 型別檢測

2021-06-18 11:48:06 字數 1341 閱讀 7853

1、檢測字串、數值、布林值、undefined、function 使用typeof(在safari和chrome中檢測正則也會返回 "function")

2、檢測null 應用「===」

3、檢測其它物件:

方法一:利用instanceof/constructor  

(再某些ie版本中存在跨iframe問題,每個iframe下都有自己的一套原型鏈,跨frame例項化的物件彼此是不共享原型鏈)

alert(a  instanceof  object)

alert(a instanceof array)

alert(a instanceof regexp)

alert(a.constructor==array)

例如:

方法二:利用 object.prototype.tostring.call()  

(解決了方法一跨iframe 失效的問題)

例如:

object.prototype.tostring.call ({})          //"[objectobject]"

object.prototype.tostring.call ([1,2,3,4]); //"[objectarray]"

object.prototype.tostring.call(newdate()); //"[objectdate]"

object.prototype.tostring.call(/^hello/); //"[objectregexp]"

object.prototype.tostring.call(newerror()) //"[objecterror]"

object.prototype.tostring.call(newnumber()) //"[objectnumber]"

參考jquery解決方案

var class2type = {};

$.each("boolean number string function array date regexp object".split(" "), function (i, name) );

$.type = function (obj) ;

另外,ecmascript 5 定義了乙個新方法array.isarray(),該函式在引數為陣列時返回true,例如

array.isarray()     // true

所以我們可以定義:

if(typeof array.isarray=="undefined")

}

JS型別檢測

主要有兩種型別檢測 typeof 以及 instanceof 一 typeof 判斷型別 返回乙個字串 typeof 數字 number typeof 布林值 boolean typeof 字串 object typeof undefined undefined typeof null object...

JS 型別檢測

型別檢測分為五種 1.typeof 2.物件 obj instanceof object 函式物件 函式構造器 左邊的運算元的物件的原型鏈上是否有右操作函式構造器的prototype屬性 例子 1,2 instanceof array true new object instanceof array...

js型別檢測

只適用與基本型別 1 console.log typeof langshen string 2 console.log typeof 666 number 3 console.log typeof true boolean 4 console.log typeof false boolean 5 c...