为什么此函数无法评估给定参数的数据类型?

时间:2011-04-18 23:07:46

标签: javascript web

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。有没有办法来解决这个问题?感谢。

5 个答案:

答案 0 :(得分:2)

是 - 在查找数组的数组类型时,请勿使用该方法查找数据类型。而是使用arr instanceof Array

答案 1 :(得分:1)

难道你不需要另一个空间吗?

'[object ' + dataType + ']'
        ^-- a space here

这不是一种测试数据类型的好方法,正如其他人已经提到的那样。

答案 2 :(得分:1)

'[object后您缺少空格。然后您的代码应评估为true。

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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