数据类型的检测方式
1. typeof:除了會把數組,null判斷為object,其它判斷都正確
console.log(typeof 2); // number console.log(typeof true); // boolean console.log(typeof 'str'); // string console.log(typeof function(){}); // function console.log(typeof {}); // object console.log(typeof []); // object console.log(typeof null); // object console.log(typeof undefined); //undefined2. instanceof:只能判斷引用數據類型,不能判斷基本數據類型。運行機制是判斷在其原型鏈中能否找到該類型的原型,所以還是會將數組判定成Object類型。
console.log(2 instanceof Number); // falseconsole.log(true instanceof Boolean); // falseconsole.log('str' instanceof String); // falseconsole.log([] instanceof Array); // trueconsole.log([] instanceof Object); // trueconsole.log(null instanceof Object); // falseconsole.log(function(){} instanceof Function); // trueconsole.log({} instanceof Object); //true3. constructor: 有兩個作用,一是判斷數據的類型,二十對象實例通過constrcutor對象訪問它的構造函數。需要注意,如果創建一個對象來改變它的原型,constructor 就不能來判斷數據類型了
console.log((2).constructor === Number); // trueconsole.log((true).constructor === Boolean); // trueconsole.log(('str').constructor === String); // trueconsole.log(([]).constructor === Array); // trueconsole.log(([]).constructor === Object); // falseconsole.log((function (){}).constructor === Function); // trueconsole.log(({}).constructor === Object); //truefunction Fn(){};Fn.prototype = new Array();var f = new Fn();console.log(f.constructor===Fn); // falseconsole.log(f.constructor===Array); // true4. Object.prototype.toString.call() 使用Object對象的原型的toString來判斷數據類型。
var a = Object.prototype.toStringconsole.log(a.call(2)); // [object Number]console.log(a.call(true)); // [object Boolean]console.log(a.call('str')); // [object String]console.log(a.call([])); // [object Array]console.log(a.call(function(){})); // [object Function]console.log(a.call({})); // [object Object]console.log(a.call(undefined)); // [object Undefined]console.log(a.call(null)); //[object Null]總結
- 上一篇: SEO快排的行业秘密,原来SEO快排套路
- 下一篇: 阿里云ECS问题大全【转自阿里云社区】