數據類型一

簡介

JavaScript 語言的每個值,都屬於某一種數據類型

原始類型數組

  • boolean
  • number
  • string

特殊值函數

  • undefined
  • null

複雜類型prototype

  • object
  • array
  • function

判斷值的類型

1.typeof 運算符code

typeof 運算符能夠返回一個值的數據類型。
typeof true             // "boolean"
typeof 100              // "number"
typeof 'Hello World'    // "string"

var fn = function() {
    console.log(str);
}
typeof fn    // "function"

var u;
typeof u     // "undefined"

// 因爲歷史緣由,null 的類型是 object
typeof null    // "object"

typeof window // "object"
typeof {}     // "object"
typeof []     // "object"

2.instanceof 運算符對象

instanceof 運算符返回一個布爾值,表示對象是否爲某個構造函數的實例。

instanceof 運算符的左邊是實例對象,右邊是構造函數。它會檢查右邊構建函數的原型對象(prototype),是否在左邊對象的原型鏈上。ip

// instanceof 運算符只能用於對象,不適用原始類型的值以及undefined,null
var s = 'hello'
s instanceof String    // false

instanceof 的用處原型鏈

var x = [1, 2, 3];
var y = {};
var date = new Date();
x instanceof Array     // true
y instanceof Object    // true
date instanceof Date      // true

3.Object.prototype.toString 方法字符串

Object.prototype.toString.call(value)
  • 數值:返回[object Number]。
  • 字符串:返回[object String]。
  • 布爾值:返回[object Boolean]。
  • undefined:返回[object Undefined]。
  • null:返回[object Null]。
  • 數組:返回[object Array]。
  • arguments 對象:返回[object Arguments]。
  • 函數:返回[object Function]。
  • Error 對象:返回[object Error]。
  • Date 對象:返回[object Date]。
  • RegExp 對象:返回[object RegExp]。
  • 其餘對象:返回[object Object]。
Object.prototype.toString.call(1)         // "[object Number]"
Object.prototype.toString.call('')        // "[object String]"
Object.prototype.toString.call(true)      // "[object Boolean]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(null)      // "[object Null]"
Object.prototype.toString.call(Math)      // "[object Math]"
Object.prototype.toString.call({})        // "[object Object]"
Object.prototype.toString.call([])        // "[object Array]"

利用這個特性,能夠寫出typeof運算符更準確的類型判斷函數原型

var type = function (o){
  var s = Object.prototype.toString.call(o);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};

type({});         // "object"
type([]);         // "array"
type(5);          // "number"
type(null);       // "null"
type();           // "undefined"
type(/abcd/);     // "regex"
type(new Date()); // "date"
相關文章
相關標籤/搜索