⼏种判断数据类型的优缺点truncate的特征
⼀、typeof
console.log(typeof1); // number
console.log(typeof true); // boolean
console.log(typeof'mc'); // string
console.log(typeof function(){}); // function
console.log(typeof []); // object
console.log(typeof {}); // object
console.log(typeof null); // object
console.log(typeof undefined); // undefined
优点:能够快速区分基本数据类型缺点:不能将Object、Array和Null区分,都返回object
⼆、instanceof
console.log(1 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
优点:能够区分Array、Object和Function,适合⽤于判断⾃定义的类实例对象缺点:Number,Boolean,String基本数据类型不能判断三、String.call()
var toString = String;
console.log(toString.call(1)); //[object Number]
console.log(toString.call(true)); //[object Boolean]
console.log(toString.call('mc')); //[object String]
console.log(toString.call([])); //[object Array]
console.log(toString.call({})); //[object Object]
console.log(toString.call(function(){})); //[object Function]
console.log(toString.call(undefined)); //[object Undefined]
console.log(toString.call(null)); //[object Null]
优点:精准判断数据类型缺点:写法繁琐不容易记,推荐进⾏封装后使⽤
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论