-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
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 judgmentsfunction 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!