Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

类型:基础知识
难度:★

实现 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');
liwenkang

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.