为什么此函数无法计算给定参数的数据类型

Why does this function fail to evaluate the data-type of a given argument?

本文关键字:参数 数据类型 计算 函数 为什么      更新时间:2023-09-26
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。有没有办法解决这个问题?谢谢。

是的

- 在查找数组的数据类型时,不要使用该方法查找数据类型。请改用arr instanceof Array .

您在 '[object 之后缺少一个空格。 然后,代码的计算结果应为 true。

但是,您应该使用 instanceof 来确定对象是否属于特定类型。

你不是只需要另一个空间吗?

'[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);
}