數據類型檢測
1.instanceof
- 判斷對象是不是構造函數的實例化
- 能夠用來作判斷已知對象的類型
- 對象與構造函數在原型鏈上是否有關係
function Person() {
this.name = "yaqi";
}
Person.prototype = {};
var p = new Person();
console.log(p instanceof Person);
var num = 1
var str = '傳智播客'
var bool=false;
var arr=[];
var obj={name:'傳智播客'};
var date = new Date();
var fn = function(){}
console.log('數據類型判斷 - typeof')
console.log(typeof undefined)
console.log(typeof null)
console.log(typeof true)
console.log(typeof 123)
console.log(typeof "abc")
console.log(typeof function() {})
var arr=[];
console.log(typeof {})
console.log(typeof arr)
console.log(typeof unknownVariable)
3.toString.call()
- 通用但很繁瑣的方法: 能夠利用Object.prototype.toString.call(arg)來判斷數據類型
console.log('數據類型判斷 - toString.call')
console.log(toString.call(123))
console.log(toString.call('123'))
console.log(toString.call(undefined))
console.log(toString.call(true))
console.log(toString.call({}))
console.log(toString.call([]))
console.log(toString.call(function(){}))
console.log(Object.prototype.toString.call(str) === '[object String]')
console.log(Object.prototype.toString.call(num) === '[object Number]')
console.log(Object.prototype.toString.call(arr) === '[object Array]')
console.log(Object.prototype.toString.call(date) === '[object Date]')
console.log(Object.prototype.toString.call(fn) === '[object Function]')
var arr=[];
console.log('數據類型判斷 - constructor')
console.log(arr.constructor === Array)
console.log(date.constructor === Date)
console.log(fn.constructor === Function)