类型判断

typeof

typof利于判断基本类型,除了null

number,string,undefined,null,boolean,symbol都能正常测验

 

null由于js的bug的问题,会显示为object

 

对于引用类型,typeof除了function之外返回的都是Object

不太适用

console.log(typeof 2);               // number
console.log(typeof true);            // boolean
console.log(typeof 'str');           // string
console.log(typeof undefined);       // undefined
console.log(typeof []);              // object 
console.log(typeof {});              // object
console.log(typeof function(){});    // function
console.log(typeof null);            // object

 

instanceof

 

instanceof有利于判断引用类型,

但是判断number boolean String则都返回false 

console.log(2 instanceof Number);                    // false
console.log(true instanceof Boolean);                // false 
console.log('str' instanceof String);                // false  
console.log([] instanceof Array);                    // true
console.log(function(){} instanceof Function);       // true
console.log({} instanceof Object);                   // true

 

 

Object.prototype.toString.call(【item】)

可以判断所有类型

var toString = Object.prototype.toString;
 
console.log(toString.call(2));                      //[object Number]
console.log(toString.call(true));                   //[object Boolean]
console.log(toString.call('str'));                  //[object String]
console.log(toString.call([]));                     //[object Array]
console.log(toString.call(function(){}));           //[object Function]
console.log(toString.call({}));                     //[object Object]
console.log(toString.call(undefined));              //[object Undefined]
console.log(toString.call(null));                   //[object Null]

 

posted @ 2021-08-26 18:57  来吃点代码  阅读(37)  评论(0编辑  收藏  举报