本帖最后由 风中瞎跑 于 2020-11-13 15:27 编辑
闲着没事写了一个js的数据类型检查小插件,路过的同行可以看看指点一二
[JavaScript] 纯文本查看 复制代码 function Detector() {
var obj = (function () {
var type = {};
for (var i = 0, arr; arr = ["Array", "Object", "String", "Number", "Undefined", "Null", "Function", "NaN"][i++];) {
(function (arr) {
type["is" + arr] = function (txt) {
return callback(arr, txt);
};
})(arr)
}
return type;
})();
function callback(str, txt) {
var str_ = str;
var str = "[object " + str + "]", state = false;
if (txt.toString() === "NaN" && str_ !== "NaN") return false;
str_ === "NaN" ?
(txt.toString() === "NaN" ? state = true : state) :
Object.prototype.toString.call(txt) === str ?
state = true : state;
return state;
};
return obj;
};
用法:
第一步:[JavaScript] 纯文本查看 复制代码 <script src="xxx/js/detector.js"></script>
第二步:[JavaScript] 纯文本查看 复制代码 const detector = new Detector();
用法:
[JavaScript] 纯文本查看 复制代码 var a="你好";
detector.isString(a)//true
detector.isNumber(a)//false
支持验证的数据类型有:
[JavaScript] 纯文本查看 复制代码 detector.isString();
detector.isNumber();
detector.isArray();
detector.isObject();
detector.isUndefined();
detector.isNull();
detector.isFunction();
detector.isNaN(); |