簡體   English   中英

為什么此函數無法評估給定參數的數據類型?

[英]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

當我使obj等於數組並將數據類型評估為數組時,它仍然表示false。 有沒有辦法解決這個問題? 謝謝。

是的-查找數組的數據類型時不要使用該方法來查找數據類型。 而是使用arr instanceof Array

您不只是需要另一個空間嗎?

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

正如其他人已經提到的那樣,這不是測試數據類型的好方法。

您在'[object之后,缺少空格。 然后,您的代碼應評估為true。

但是,您應該使用instanceof來確定對象是否為特定類型。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM