DIV CSS 佈局教程網

JavaScript 的 typeof 運算子用法與實例
編輯:JavaScript基礎知識     

對一個值使用 typeof 運算子,可能得到以下幾種字串結果:

  • "undefined"——值尚未定義
  • "boolean"——布林值
  • "string"——字串
  • "number"——數值
  • "object"——物件或 null
  • "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 的操作數既可以是變數,也可以是字面值。要記住的是,typeof 是一個運算子而非函數,因此後面的圓括號並非必要(當然加上也沒問題)。

值得留意的是,用 Number() 建立的數字會被 typeof 判斷為物件並回傳 "object",這是因為所有構造函數回傳的都是物件。那麼若想精確區分 Number、String、Array、Function、Date、Boolean、Error 等內建物件,該怎麼辦呢?這時可以借用 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]"

// ...
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved