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

第 14 期(2019-05-21):类型判断 #16

Open
wingmeng opened this issue May 21, 2019 · 1 comment
Open

第 14 期(2019-05-21):类型判断 #16

wingmeng opened this issue May 21, 2019 · 1 comment

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented May 21, 2019

类型:基础知识
难度:★

实现 isObject(X), isString(X), isArray(X) 三个方法,用以判断是否为对应类型,返回布尔值

测试用例:

isObject([1, 2]);  // false
isString(123);  // false
isArray({a: 1});  // false

isObject({a: 1});  // true
isString('123');  // true
isArray([1, 2]);  // true

参考答案:

非常有价值的一段代码,类型判断的神码,函数柯里化的入门级教学代码。(来自 seajs 源码)

function isType(type) {
  return function(obj) {
    return Object.prototype.toString.call(obj) === '[object ' + type + ']'
  }
}

var isObject = isType('Object');
var isString = isType('String');
var isArray = Array.isArray || isType('Array');
@AMY-Y
Copy link

AMY-Y commented May 22, 2019

        function isObject(x){
            return x instanceof Object;
        }       
        function isString(x){
            return x instanceof String || typeof x == 'string';
        }       
        function isArray(x){
            return x instanceof Array;
        }  

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants