You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
PS: 常用的对象类型判断方法中,Object.prototype.toString.call()是我目前接触过判断类型最准确的方法,只有 NaN 会判断为number,特殊处理一下就好。其它方式中,typeof NaN 和 numer 均会判断为 number,[] , {}, Date 和 null等均会判断为 object ;instanceof返回类型为boolean,单个判断某对象是否为某类型, 个人认为可用于针对某种类型去判断,不太适合运用在集成判断类型的方法中。
// 判断对象类型
// 测试用例
var arr = [];
var obj = {};
var date = new Date();
var fun = function() {};
var num = 0;
var str = "";
var n = null;
var nan = NaN;
var bool = true;
var un = undefined;
// 类型集合
var _type = [arr, obj, date, num, str, n, fun, nan, bool, un];
function getType(value) {
if (typeof value == 'number' && isNaN(value)) {
return "[object NaN]";
}
return Object.prototype.toString.call(value);
}
function getObjType(obj) {
var typeList = [];
for(var i = 0; i < obj.length; i++) {
var itemType = getType(obj[i]);
typeList.push({ item: obj[i], type: itemType });
}
return typeList;
}
console.log(getObjType(_type));
The text was updated successfully, but these errors were encountered: