使用Object物件的toString()方法自定義判斷資料型別方法
阿新 • • 發佈:2019-01-27
Object.prototype.toString方法返回物件的型別字串
Object.prototype.toString.call(2) // "[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 dataType = function(o){
var s = Object.prototype.toString.call(o);
return s.match(/\[object (.*?)\]/)[1].toLowerCase();
}
dataType([]); // "array"
專門判斷某一個型別
['Null', 'Undefined', 'Object', 'Array', 'String', 'Number', 'Boolean', 'Function', 'RegExp', 'NaN', 'Infinite'].forEach(function(item){
dataType['is' + item] = function(o){
return dataType(o) === item.toLowerCase();
}
})
dataType.isObject({}) // true