欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

javascript 得到變量類型的函數(shù)

 更新時間:2010年05月19日 19:07:56   作者:  
在JavaScript中,有時需要準確知道一個變量的類型,顯然typeof函數(shù)不能滿足這個要求,這個函數(shù)在大多數(shù)情況下都返回object。
這個功能需要寫一點代碼來實現(xiàn)。下面的函數(shù)可以得到一個變量的類型,調用時傳遞一個變量進去,會返回用字符串形式描述的變量類型。
復制代碼 代碼如下:

//得到x的類型,返回類型名稱
function getType(x) {
//如果x為null,則返回null
if (x == null) return "null";
var t = typeof x;
//如果x為簡單類型,則返回類型名稱
if (t.toLocaleLowerCase() != "object") return t;
//調用object類的toString方法得到類型信息
//object.toString方法返回類似這樣的信息[object 類名]
t = Object.prototype.toString.apply(x).toLowerCase();
//截取toString方法返回值的類名部分
t = t.substring(8, t.length - 1);
if (t.toLocaleLowerCase() != "object") return t;
//檢查x確實為object類型
if (x.constructor == Object) return t;
//從構造函數(shù)得到類型名稱
if (typeof x.constructor == "function")
return getFunctionName(x.constructor);
return "unknow type";
}
//得到函數(shù)名稱
function getFunctionName(fn) {
if (typeof fn != "function") throw "the argument must be a function.";
var reg = /\W*function\s+([\w\$]+)\s*\(/;
var name = reg.exec(fn);
if (!name) {
return '(Anonymous)';
}
return name[1];
}

相關文章

最新評論