![](/img/trans.png)
[英]What data-type does a TypeScript property need to be passed a function in a React component
[英]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.