js obtain any data class or type is determined General procedure (getDataType) and into the NodeList array (NodeListToArray) ...

Original link: http://www.cnblogs.com/yzryc/p/6053119.html

getDataType function (the any)
{
/ * (. 1) The method of determining the type Object.prototype.toString.call:
advantages: General, returns "[object String]" type specific object of
disadvantages: the type of inheritance can not return

(2) typeof x
disadvantage : the object type is not broken;
advantages: determining a null empty 'undefined' application;
return types: 'undefined' "String" 'Number' 'Boolean' 'function' 'object'

(. 3) to return the instanceof specific type, only applies to the determination of new objects created with a keyword
* /
// the baseType var = [ "String", "Number", "Boolean"]; // basic types
// var refType = [ "object" , "Function", "Array", "Date"]; // reference type


the try
{
var DTYPE = Object.prototype.toString.call (the any);
IF (DTYPE == "[Object Object]") // IE, an element object dom
{

the try
{
IF (any.constructor)
{
var constructorStr=any.constructor.toString(); //obj.constructor可以返回继承的类型
if(constructorStr.indexOf("Array")!=-1) { dtype="[object Array]"; }
else
if(constructorStr.indexOf("HTMLCollection")!=-1) { /* IE */ dtype="[object NodeList]"; }

else
if((constructorStr.indexOf("function")!=-1) && (constructorStr.indexOf("Object()")!=-1))
{
dtype="[object Object]";
}
else
dtype=constructorStr;
}
}
catch(e)
{
return "[object Null]";
}


}
else
{
if(dtype=="[object HTMLCollection]") { /* FF */ dtype="[object NodeList]"; }


}

return dtype;


}catch(e)
{
return "variable is not defined.";
}



}

 

// NodeList into the array, so that the method can use all NodeList array
function NodeListToArray (Nodes) {
var Array = null;
the try {
Array = Array.prototype.slice.call (Nodes, 0);
} the catch (EX) {
the Array = new new Array ();
for (var I = 0, len = nodes.length; I <len; I ++) {
Array.push (Nodes [I]);
}
}

return array;
}

 

/* //测试 getDataType 方法
var aa=null;
alert(getDataType(aa));
var abc;
alert(getDataType(abc)); //[object Undefined] 说明此变量已经声明,但尚未被初始化
var fn=function(){}
alert(getDataType(fn)); //[object Function]
alert(getDataType(new Object())); //[object Object]
alert(getDataType("Hello"));//[object String]
alert(getDataType(234));//[object Number]
alert(getDataType(true));//[object Boolean]
alert(getDataType(new Date())); //[object Date]
alert(getDataType(new Date().getTime())); //[object Number]
alert(getDataType(document.getElementById("demopic"))); //[object HTMLDivElement]
var nodelist=NodeListToArray(document.getElementsByTagName("*"));
alert(getDataType(nodelist)); //[object Array]
alert(getDataType(document.getElementsByTagName("*"))); //[object NodeList)]
//alert(nodelist[10].tagName);
alert(getDataType(/[a-z]/)); //[object RegExp]
*/

 

Reproduced in: https: //www.cnblogs.com/yzryc/p/6053119.html

Guess you like

Origin blog.csdn.net/weixin_30455067/article/details/94795446