JS如何判斷資料型別

2021-10-24 23:07:30 字數 1642 閱讀 8229

首先我們要清楚基本型別與引用型別分別是指什麼。

基本型別:undefined、null、string、number、boolean、symbol(es6)

引用型別:object、array、regexp、date、function

1.typeof

typeof的返回值一共有七種,分別為"string","number","boolean",「object」,"function","undefined"以及es6新增的"symbol"。

如果我們想用 typeof 來判斷array,object,還有null型別的話返回的結果都為「object」型別,沒辦法判斷該變數是陣列、物件還是空型別。若需要判斷array,object,null的話則可以用typeof封裝一下

let gettype = function (val)  else if (typeof val === 'object')  else 

} else

}

若覺得封裝成函式麻煩的可以看下以下幾種方法。

2.instanceof

let array = [1, 2, 3];

console.log(array instanceof array); //true

let obj={};

console.log(obj instanceof object); // true

3.constructor

let array = [1,2,3,1];

console.log(array.constructor === array); // true

4、object.prototype.tostring

let array = [1, 2, 3];

let obj = {};

console.log(object.prototype.tostring.call(obj)); //[object object]

console.log(object.prototype.tostring.call(array)); //[object array]

這種方法的返回值是乙個字串型別,如果只希望返回值為資料型別,而不包含[object array]前面的object的話,可以做以下封裝

function gettype(val) 

let array = [1, 2, 3];

gettype(array)

該函式的返回值就僅僅是傳入引數的資料型別了。

5.array.isarray()

好像這種方法只能用於判斷陣列型別

let array = [1, 2, 3];

console.log(array.isarray(array)); //true

以上是我個人所得知的幾種判斷資料型別的幾種方法。

js判斷資料型別

1 typeof 形如 var x xx typeof x string 返回型別有 undefined string number boolean function object 缺點 對於object型別不能細分是什麼型別 優點 對空null的判斷 undefined 的應用 2 instanc...

js判斷資料型別

了解js的都知道,有個typeof 用來判斷各種資料型別,有兩種寫法 typeof typeof 如下例項 typeof 2 輸出 number typeof null 輸出 object typeof 輸出 object typeof 輸出 object typeof function 輸出 fu...

js判斷資料型別

1 判斷是否為陣列型別 2 判斷是否為字串型別 3 判斷是否為數值型別 isnan 變數 如果為true就是數字型別 注意這個函式一般針對數字型別來判斷是否值為nan,若變數為非數字型別,則先轉化為數字型別再做判斷,用此函式時,別忘考慮空串和空格 這倆轉化為數字是0 4 判斷是否為日期型別 5 判斷...