JavaScript中的typeof操作符用法執行個體

來源:互聯網
上載者:User

 在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]" // ... 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.