本文主要是介绍关于数据类型的判断不使用typeof的精确定位,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.JavaScript 里使用 typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object” 五种。
对于数组、函数、对象来说,其关系复杂,若使用 typeof 都会统一返回 为object,这样为后续处理带来不便。
2.关键函数方法
js原生方法Object.prototype.toString.call();它可以给出数据的确切类型,相比typeof要精确。
代码如下:
function getDataType(data){ var getType=Object.prototype.toString; var myType=getType.call(data);//调用call方法判断类型,结果返回形如[object Function] var typeName=myType.slice(8,-1);//[object Function],即取除了“[object ”的字符串。 var copyData='';//复制后的数据 //console.log(data+" is "+myType); switch(typeName){ case 'Number': copyData=data-0; break; case 'String': copyData="'"+data+"'"; break; case 'Function': copyData=data; break; case 'Null': copyData=null; break; case 'Undefined': copyData="Undefined"; break; case 'Array': copyData=[];//先将copyData变为空数组 for(var i=0;i<data.length;i++){ copyData[i]=data[i];//将data数组数据逐个写入copyData } break; case 'Object': copyData={};//先将copyData变为空对象 for(var x in data){ copyData[x]=data[x]; } break; case 'Boolean': copyData=data; break; default : copyData=data; break; } return copyData;
}
console.log(getDataType(123));
console.log(getDataType("123"));
console.log(getDataType(null));
console.log(getDataType(undefined));
console.log(getDataType(false));
console.log(getDataType([1,2,4]));
console.log(getDataType({"name":"wc"}));
console.log(getDataType(function(){alert(23);}));
运行结果
123
‘123’
null
Undefined
false
[1,2,4]
Object{name: ‘wc’}
function(){alert(23)}
这篇关于关于数据类型的判断不使用typeof的精确定位的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!