Jump to content

Javascript Function: datatypeof


ApocalypeX

Recommended Posts

So I don't think this subforum has been used to critique code snippets. I wrote a little function that gives out correct datatypes of JavaScript variables/objects. I would like to add it to something larger, maybe jQuery, but that's not really important at the moment.Any problems you encounter or refinements you have please do post them.

var datatypeof = function(data, v){	var verbose = v || false,	datatype = (typeof data);	switch (datatype){		case "object":			if(data === null){				datatype = "null";			}			else if(data.push !== undefined){				if(data.hasOwnProperty("push")){					datatype = "object";							}				else{					datatype = "array";				}			}			else if(data.constructor() === (new Date()).constructor() && data !== undefined){				datatype = "date";			}			else{				datatype = "object";			}			break;		case "number":			datatype = ((verbose) ? (function(){				var reg = /[0-9](\.)[0-9]/,				point = reg.test(data.toString());				return ((point) ? "float" : "int");			}()) : "number");			break;		case "function":			if(data.constructor() === (new RegExp()).constructor()){				datatype = "regexp";			}			break;	}	return datatype;};

An example of it in use is:

datatypeof(1);datatypeof(1.1);datatypeof(1.1, true);datatypeof(new Date());

Link to comment
Share on other sites

Looks pretty clean. Obviously you are targeting certain data types rather than writing a comprehensive function.There should be no reason to reset the value of datatype to 'object' if that is the value already. In the first place this happens, a break statement would do. In the second, the final else structure in the object case can be deleted (or if you like it for reading clarity, comment out the assignment statement).EDIT. Actually, given the tightly controlled structure, you could reverse the first if-else structure so that it tests for an array condition first, and if that is not the condition, no additional statements would be necessary. datatype would remain set to "object" without additional statements.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...