Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第九题:写一个判断对象类型的方法 #9

Open
Ray-56 opened this issue Aug 19, 2019 · 2 comments
Open

第九题:写一个判断对象类型的方法 #9

Ray-56 opened this issue Aug 19, 2019 · 2 comments
Labels
JavaScript 解释型编程语言

Comments

@Ray-56
Copy link
Owner

Ray-56 commented Aug 19, 2019

写一个判断对象类型的方法,考虑兼容性

@Ray-56 Ray-56 added the JavaScript 解释型编程语言 label Aug 19, 2019
@GenXiaoLe
Copy link
Collaborator

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 printType(result) {
  for(var i = 0; i < result.length; i++) {
    var _item = result[i];

    if (typeof(_item) == 'number' && isNaN(_item)) {
      console.log('[object NaN]');
      continue;
    }
    console.log(Object.prototype.toString.call(_item))
  }
}
printType(_type);

PS: 常用的对象类型判断方法中,Object.prototype.toString.call()是我目前接触过判断类型最准确的方法,只有 NaN 会判断为number,特殊处理一下就好。其它方式中,typeof NaN 和 numer 均会判断为 number,[] , {}, Date 和 null等均会判断为 objectinstanceof返回类型为boolean,单个判断某对象是否为某类型, 个人认为可用于针对某种类型去判断,不太适合运用在集成判断类型的方法中。

@MMmaXingXing
Copy link

// 判断对象类型
// 测试用例
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));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript 解释型编程语言
Projects
None yet
Development

No branches or pull requests

3 participants