问题描述
|
function isDataType(dataType,obj) {
return Object.prototype.toString.call(obj) == \'[object\' + dataType + \']\';
}
var arr = [];
alert(isDataType(\"Array\",arr)); // alerts \'false\' which is false
当我使obj等于数组并将数据类型评估为数组时,它仍然表示false。有没有办法来解决这个问题?谢谢。解决方法
您在
\'[object
之后缺少空格。然后,您的代码应评估为true。
但是,您应该使用instanceof来确定对象是否为特定类型。,是的-查找数组的数据类型时不要使用该方法来查找数据类型。而是使用arr instanceof Array
。,您不只是需要另一个空间吗?
\'[object \' + dataType + \']\'
^-- a space here
正如其他人已经提到的那样,这不是测试数据类型的好方法。,function is(type,obj) {
var clas = Object.prototype.toString.call(obj).slice(8,-1);
return obj !== undefined && obj !== null && clas === type;
}
is(\'String\',\'test\'); // true
is(\'String\',new String(\'test\')); // true
,function whatsit(what){
if(what== null) return String(what);
what= what.constructor;
var Rx= /function\\s+([^(\\s]+)\\s*\\(/,tem= String(what).match(Rx);
if(tem) return tem[1];
return String(what);
}