开发者

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

function isDataType(dataType, obj) {
    return Object.prototype.toString.call(obj) == '[object' + dataType + ']';
}

var arr = [];

alert开发者_开发技巧(isDataType("Array", arr)); // alerts 'false' which is false

When I make obj equal to an array and make the data type to evaluate as an array, it still says false. Is there a way to fix this? Thanks.


Yes - don't use that method to find datatypes when finding datatypes of Arrays. Instead use arr instanceof Array.


You are missing a space after '[object. Your code should then evaluate to true.

You should use instanceof to find out if an object is of a specific type, though.


Don't you just need another space?

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

This isn't a great method for testing for datatypes, as others have already mentioned.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜