JavaScript中数据类型检测

1、typeof

对于基本类型来说,typeof就足够了,但是引用类型不行,因为所有的引用类型都是对象,所以对引用类型使用typeof返回的都是object。

不能检测引用类型和null

var a = 1234;
typeof a;   // "number"
var str = 'hello';
typeof str; // "string"
var boo = false;
typeof boo; // "boolean"
var un = undefined
typeof un;  // "undefined"
var nu = null
typeof nu;  // "object"

typeof {};  // "object"
typeof [];  // "object"
typeof new Date();  // "object"
typeof new RegExp();    // "object"
typeof checkJSONstr     // function
function checkJSONstr(){}

2、instanceof

使用instanceof作为检测的原理是,前者是不是后者的实例。
但是用instanceof判断是浏览器原生对象还是用户自定义的对象时,不能准确判断。且不能检测字面量方式创建的基本类型。

不能检测null和undefined

var arr = [];
arr instanceof Array;   // true

var date = new Date();
date instanceof Date;   // true

3、Object.prototype.toString.call()

原理是,在任何值上调用Object的prototype上的toString,都会返回一个[object NativeConstructorName]格式的字符串,每个类在内部都有一个[[Class]]属性,这个属性中就指定了上述字符串中的构造函数名。

==前提是Object.prototype.toString()没有被重写==。

Object.prototype.toString.call(new Date());           // "[object Date]"
Object.prototype.toString.call([]);                   // "[object Array]"
Object.prototype.toString.call({});                   //"[object Object]"
Object.prototype.toString.call(new RegExp());         // "[object RegExp]"
// 判断是否是原生的JSON对象
Object.prototype.toString.call(JSON);                 //"[object JSON]"
Object.prototype.toString.call(undefined);            // "[object Undefined]"
Object.prototype.toString.call(null);                 //"[object Null]"
Object.prototype.toString.call('');                   // "[object String]"
Object.prototype.toString.call(12344);                // "[object Number]"
Object.prototype.toString.call("false")               //"[object String]"
Object.prototype.toString.call(false);                //"[object Boolean]"
Object.prototype.toString.call(function(){});         //"[object Function]"

4、构造函数

不能检测Null和Undefined;并且如果类的构造函数被修改了,就不能检测了。

'heelo'.constructor === String;         // true
Number('heelo').constructor === Number;     // true
Boolean('hello').constructor === Boolean;   // true
[].constructor === Array;   // true
[].constructor === Object;  // false

var a = {1:1};
a.constructor === Object;   // true
new Date().constructor === Date;    // true


null.constructor === Null
VM2553:1 Uncaught TypeError: Cannot read property 'constructor' of null
    at <anonymous>:1:6

5. 实例

(1)封装一个函数,输入任意值,输出它的类型。
function checkType(target) {
    let res = Object.prototype.toString.call(target);
    res = res.split(' ')[1].replace(/\]/g, '');
    return res;
}
(2)如何判断一个字符串是否为JSON类型的字符串
function checkJSONstr(str) {
    if (typeof str === 'string') {
        try{
            if(typeof JSON.parse(str) === 'object') {
                return true;
            } 
        } catch(e) {
            console.log(e);
        }
        
    } 
    return false;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容