如何判斷變數型別

2021-09-11 14:17:01 字數 2836 閱讀 6579

在js中如何判斷變數的型別屬於基礎知識,很多時候我們會忽略。畢竟上手**的時候可以現查。無論如何演變,我想基本功還是很重要的,熟練掌握總是百利而無一害。

1、首先第一種就是我們常用的typeof(),它會將型別資訊當作字串返回。如下:

console.log(typeof undefined); //undefined

console.log(typeof 5); //number

console.log(typeof true); //boolean

console.log(typeof 'hello world!'); //string複製**

很完美對不對?但我們知道,這個世界幾乎沒有什麼是完美的。看看下面的栗子就知道了:

console.log(typeof ['h', 'e', 'l', 'l', 'o']); //object

console.log(typeof ); //object

console.log(typeof null); //object

console.log(typeof new date()); //object複製**

列印出來的結果都是object型別。通過上面的列印結果,我們知道typeof在判斷變數型別的時候比較適合用來處理基本資料型別,如果是引用型別的值,typeof恐怕就心有餘而力不足了。

2、instanceof:該運算子用來測試乙個物件在其原型鏈中是否存在乙個建構函式的 prototype 屬性。

let arr = [1, 2, 3];

let obj = ;

console.log(obj instanceof array); //false

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

複製**

通過instanceof很容易就能判斷乙個變數是陣列還是物件,貌似比typeof要高階了一些。但如果遇到陣列,情況可能跟我們想象的不一樣了。

let arr = [1, 2, 3];

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

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

複製**

為什麼都是true呢?看看上面instanceof運算子的定義,是用來測試乙個物件在原型鏈上是否存在乙個建構函式的prototype屬性。只要熟悉原型鏈就會知道,每個物件都有乙個__proto__屬性,指向建立該物件的函式的prototype。instanceof的判斷規則是通過__proto__和prototype能否找到同乙個引用物件。通過列印下面的等式,我們就能知道為什麼上面的栗子都會列印出true。

console.log(arr.__proto__.__proto__ === object.prototype); //true

console.log(arr.__proto__ === array.prototype); //true

複製**

3、constructor:此屬性返回對建立此物件的陣列函式的引用

let arr = [1, 2, 3];

let obj = ;

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

console.log(arr.constructor === object); //false

console.log(obj.constructor === array); //false

console.log(obj.constructor === object); //true

複製**

可以判斷基本資料型別:

console.log(object.prototype.tostring.call(3)); //[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('hello')); //[object string]

console.log(object.prototype.tostring.call(undefined)); //[object undefined]複製**

也可以判斷引用資料型別:

let arr = [1, 2, 3];

let obj = ;

let date = new date();

function

fn();

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

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

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

console.log(object.prototype.tostring.call(fn)); //[object function]複製**

以上。

Python如何判斷變數的型別

python判斷變數的型別有兩種方法 type 和 isinstance 對於基本的資料型別兩個的效果都一樣 type ip port 219.135.164.245 3128 if type ip port is list print list陣列 else print 其他型別 isinstan...

php如何判斷某變數的型別

gettype 用來取得變數的型別。返回的型別字串可能為下列字串其中之一 integer double string array object unknown type is numeric mixed var 檢驗測定變數是不是為數碼或數碼字串 is bool 檢驗測定變數是不是是布林型 is f...

Python 判斷變數型別

資訊來自於如下 使用python判斷變數型別時候要使用 isinstance 函式而非 type 函式進行判斷 比如 a 111 isinstance a,int trueisinstance 和 type的區別在於 class a pass class b a pass isinstance a ...