判斷資料型別的方式

2021-08-21 05:26:32 字數 1718 閱讀 5004

1、typeof

常用來判斷基本資料型別,當判斷的是引用資料型別時返回的都是 'object'

返回的結果一共 6 種(都是字串型別的):'number'、 'string' 、'boolean' 、'undefined'、 'object'、 'function'

2、object.prototype.tostring.call()

console

. log(

object

.prototype.tostring.

call(

'1'))

// "[object string]"

console

. log(

object

.prototype.tostring.

call(

1))

// "[object number]"

console

. log(

object

.prototype.tostring.

call(

true))

// "[object boolean]"

console

. log(

object

.prototype.tostring.

call(

null))

// "[object null]"

console

. log(

object

.prototype.tostring.

call(

undefined))

// "[object undefined]"

console

. log(

object

.prototype.tostring.

call({}))

// "[object object]"

console

. log(

object

.prototype.tostring.

call())

// "[object array]"

console

. log(

object

.prototype.tostring.

call(

function

fn(){}))

// "[object function]"

console

. log(

object

.prototype.tostring.

call(

newdate()))

// "[object date]"

console

. log(

object

.prototype.tostring.

call(

/^a$

/))

// "[object regexp]"

3、instanceof

判斷乙個例項是否屬於乙個類,只能用於引用資料型別,對於基本資料型別是不准的。

用來測試乙個物件在其原型鏈中是否存在乙個建構函式的prototype屬性。

4、constructor

constructor 是 prototype 中的屬性,指向的是建構函式。

a.constructor 指向的是 a 所屬類的原型上的 constructor。

判斷資料型別的幾種方式

通常判斷js中的資料型別有常用的幾種方式 判斷基本資料型別 typeof 判斷復合資料型別 instanceof 判斷全部的資料型別 object.prototype.tostring.call var sum 23 var str 王八蛋 var obj var arr 1,2,3,54,56,7...

js判斷資料型別的幾種方式

資料型別分為 基礎資料型別和引用 物件 資料型別 基礎資料型別 number string boolean undefined null 常見的引用資料型別 funciton object array 第一種,當資料型別是undefined null 時,可以用 來進行判斷 undefined un...

判斷資料型別

typeof 如果使用typeof來判斷資料型別的話,結果如下 var num new number 123 var str new string 1223 var bool new boolean false console.log typeof 123,number typeof num,obj...