Charles Ye's blog


  • Home

  • About

  • Tags

  • Categories

  • Archives

lodash源码解读系列(1)

Posted on 2020-05-24

Lodash的类型检测

js是一种弱类型动态语言,很多时候为了代码的健壮性,必须对变量进行类型检查。查看 Lodash 源码这样的检查比比皆是,因此希望进行一番整理。

JavaScript的类型系统

JavaScript的类型有两类: 原始数据类型(Primitive Data Type)以及引用数据类型(Reference Data Type):

原始数据类型

  • undefined/null
  • boolean
  • number
    • NaN
    • Infinite
    • 数值
  • string
  • symbol
  • bigint

其中bigint是ES2020新引入类型,用于表示任意精度的整数值

引用数据类型

  • Object
    • Array
    • Function
    • Date
    • Error
    • Set
    • Map
    • WeakSet
    • WeakMap

Number类检测

isNumber

源码

1
2
3
4
function isNumber(value) {
return typeof value === 'number' ||
(isObjectLike(value) && getTag(value) == '[object Number]')
}

解读:

此处除了考虑value为数值外,还有可能是 Number 对象。
isObjectLike用于判断 value 为非 null 的对象,getTag函数调用了 Object.prototype.toString 来获取内部 [[class]] 属性,进而判断对象的类型

isObject

源码

1
2
3
4
function isObject(value) {
const type = typeof value
return value != null && (type === 'object' || type === 'function')
}

解读:

此处判断变量是否为 object 时,Lodash 将特殊值 null 排除在外,同时注意保留 typeof 为 function 的情况。

isInteger

源码

1
2
3
 function isInteger(value) {
return typeof value == 'number' && value == toInteger(value);
}

toInteger函数可将 number,字符串形式的数字转换为整数,如果结果仍然和原值相等,说明此数字为整数。

Charles Ye's Blog

Posted on 2020-04-09

Hello World

Posted on 2020-04-09

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment

Charles Ye

3 posts
1 tags
© 2020 Charles Ye
Powered by Hexo
|
Theme — NexT.Pisces v5.1.4