標籤:方法傳回值 case instance reg def new return ber typeof
1.資料類型
JavaScript一共有六種資料類型。(ES6新增了第七種Symbol類型的值)
- 數值(Number)
- 字串(String)
- 布爾值(boolean)
- undefined
- null
- 對象(object)
2.資料類型判斷
JavaScript有三種方法,可以判斷一個值的類型
- typeof運算子
- instanceof運算子
- Object.prototype.toString()方法
typeof運算子
typeof運算子可以返回一個值的資料類型。
數值、字串、布爾值分別返回number、string、boolean。
typeof 123 //"number"typeof ‘hello‘ //"string"typeof true //"boolean"
函數返回function。
function f(){} typeof f //"function"
undefined返回undefined。
typeof undefined // "undefined"
對象返回object。
typeof {} // "object"typeof [] // "object"
null返回object`。
typeof null // "object"
instanceof運算子
instanceof運算子返回一個布爾值,表示對象是否為某個建構函式的執行個體。
由於instanceof檢查整個原型鏈,因此同一個執行個體對象,可能會對多個建構函式都返回true。
instanceof運算子的一個用處,是判斷值的類型。
var x = []var f={}x instanceof Array //truef instanceof Object //true
instanceof運算子只能用於對象,不適用原始類型的值。
利用instanceof運算子,還可以解決,調用建構函式時,忘了加new命令的問題。
function Fn (f1, f2) { if (this instanceof Fn) { this._foo = f1; this._bar = b2; } else { return new Fn(f1, f2); }}
Object.prototype.toString()
toString方法的作用是返回一個對象的字串形式,預設情況下傳回型別字串。
var o1 = new Object();o1.toString() //"[object Object]"
toString() 的應用:判斷資料類型
Object.prototype.toString方法返回對象的類型字串,因此可以用來判斷一個值的類型。
var obj = {};obj.toString() // "[object Object]"
上面代碼調用Null 物件的toString方法,結果返回一個字串object Object,其中第二個Object表示該值的建構函式。這是一個十分有用的判斷資料類型的方法。
由於執行個體對象可能會自訂toString方法,覆蓋掉Object.prototype.toString方法,所以為了得到類型字串,最好直接使用Object.prototype.toString方法。通過函數的call方法,可以在任意值上調用這個方法,判斷這個值的類型。
Object.prototype.toString.call(value)
上面代碼錶示對value這個值調用Object.prototype.toString方法。
不同資料類型的Object.prototype.toString方法傳回值如下。
Object.prototype.toString.call(12) //"[object Number]"
Object.prototype.toString.call(‘ab‘) //"[object String]"
Object.prototype.toString.call(true) //"[object Boolean]"
- undefined:返回
[object Undefined]。
Object.prototype.toString.call(undefined) //"[object Undefined]"
Object.prototype.toString.call(null) //"[object Null]"
Object.prototype.toString.call([]) //"[object Array]"
var f = function (){}Object.prototype.toString.call(f) //"[object Function]"
利用這個特性,可以寫出一個比typeof運算子更準確的類型判斷函數。
var type = function (o){ var s = Object.prototype.toString.call(o); return s.match(/\[object (.*?)\]/)[1].toLowerCase();};type({}); // "object"type([]); // "array"type(3); // "number"type(null); // "null"type(); // "undefined"type(/abcd/); // "regex"type(new Date()); // "date"
未完待續
01.javascript之資料類型