在Web前端開發中,我們經常需要判斷變數的資料類型。鑒於ECMAScript是鬆散類型的,因此需要有一種手段來檢測給定變數的資料類型——typeof就是負責提供這方便資訊的操作符。
對一個值使用typeof操作符可能返回下列某個字串:“undefined”——如果這個值未定義“boolean”——如果這個值是布爾值“string”——如果這個值是字串“number”——如果這個值是數值“object”——如果這個是對象或null“function”——如果這個值是函數 常用的typeof操作符的傳回值包括number、string、boolean、undefined 、object和function。如: 代碼如下:var n;console.log(typeof n); // "undefined" n = 1;console.log(typeof n); // "number" n = "1";console.log(typeof n); // "string" n = false;console.log(typeof n); // "boolean" n = { name: "obj" };console.log(typeof n); // "object" n = new Number(5);console.log(typeof n); // "object" n = function() { return; };console.log(typeof n); // "function" 這幾個例子說明,typeof操作符的運算元可以是變數(message),也可以是數值字面量。注意,typeof是一個操作符而不是函數,因此例子中的圓括弧不是必須的(儘管可以使用)。 從上面的例子中,我們發現用Number()建立的數字也會被typeof判定為對象而傳回值“object”,這是因為建構函式返回的都是對象,那麼如果我們想要區分數字對象(Number)、字串對象(String)、數組對象(Array)、Function對象、日起對象(Date)、布爾對象(Boolean)以及錯誤對象(Error)等JavaScript內建對象時,怎麼辦呢?在這裡可以調用對象的toString方法,如: 代碼如下:var n, res; n = new Number(66);res = Object.prototype.toString.call(n);console.log(res); // "[object Number]" n = new String("string");res = Object.prototype.toString.call(n);console.log(res); // "[object String]" n = [];res = Object.prototype.toString.call(n);console.log(res); // "[object Array]" // ...