由于对检测数据类型的需求不断出现,我写了以下函数,到目前为止效果很好,所以我想把代码分享给你。但是我开始认为这可能不是类型检测的有效方法。我怎样才能增强这个功能?还是我犯了一个错误,甚至不应该这样做?
根据 cade 的回答,我查看并编辑了代码:
function detectType(data) {
// analyze data to distinguish object types from primitive types
var dataType = typeof data;
var toClass = {}.toString; // this is used to detect object types
var isPrimitive;
var isFalsy = false;
switch(dataType) {
case 'string':
isFalsy = !data;
if(isFalsy) {
dataType = 'empty string'; // Only if you want to distingush empty strings
}
isPrimitive = true;
break;
case 'number':
isFalsy = !data;
if(isFalsy) {
if(isNaN(data))
dataType = 'NaN'; // it is strange that JavaScript considers NaN a number
else {
dataType = '0'; // only needed if you want to distinguish zeros
if(1/data < 1/0)
dataType = '-0';
}
} else if(!isFinite(data)) { // Although infinity is considered a number you might want to distinguish it
dataType = 'infinity';
if(data < Infinity)
dataType = '-infinity';
}
isPrimitive = true;
break;
case 'boolean':
isFalsy = !data;
isPrimitive = true;
break;
case 'object':
isFalsy = !data;
dataType = toClass.call(data).slice(8, -1).toLowerCase();
switch(dataType) {
case 'string':
dataType = 'object string';
break;
case 'number':
dataType = 'object number';
break;
case 'boolean':
dataType = 'object boolean';
break;
}
isPrimitive = false;
break;
case 'function':
isFalsy = !data;
isPrimitive = false;
break;
case 'undefined':
isFalsy = !data;
isPrimitive = false;
break;
}
return [dataType, isPrimitive ,isFalsy];
}
我在控制台中尝试了一些东西并得到了这些结果:
detectType(-0)
["-0", true, true]
detectType(9)
["number", true, false]
detectType(new Number(3))
["object number", false, false]
detectType('')
["empty string", true, true]
detectType('foo')
["string", true, false]
detectType(new String('bar'))
["object string", false, false]
detectType(true)
["boolean", true, false]
detectType(new Boolean(false))
["object boolean", false, false]
detectType(document.body)
["htmlbodyelement", false, false]
detectType(-0)
["-0", true, true]
detectType(-Infinity)
["-infinity", true, false]
detectType(/a-zA-Z/)
["regexp", false, false]
现在它甚至可以检测 html 元素,可以检查 -0、+0 和 -Infinity、+Infinity,虽然这些被认为是数字,但人们可能会发现区分太大或太小的数字很有用,例如无穷大或-0。