Skip to content

How to accurately determine the type of js object #74

@openHacking

Description

@openHacking

1. Distinguish between array and object

var arr = [1, 2, 3];

var obj = {"a": 3, "b": 4};

Judgment array: typeof arr == "object" && arr.length != undefined

or arr instanceof Array == true

Note: arr instanceof Object == true, so instanceof and typeof cannot be used alone to judge objects

Judging the object: typeof obj== "object" && obj.length == undefined

Principle: (1) Both arrays and objects use typeof to be object

(2) Object has no length

 

2. Determine the data type:

Generic functions for writing data type judgments
function getType(obj){
var toString = Object.prototype.toString;
var map = {
'[object Boolean]' : 'boolean',
'[object Number]' : 'number',
'[object String]' : 'string',
'[object Function]' : 'function',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object RegExp]' : 'regExp',
'[object Undefined]': 'undefined',
'[object Null]' : 'null',
'[object Object]' : 'object'
};
if(obj instanceof Element) {
return 'element';
}
return map[toString.call(obj)];
}

Quoted from: sysuzhyupeng Thanks!

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions