最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why lodash .isNumber function is more complicated than typeof value == 'number' - Stack Overflow

programmeradmin6浏览0评论

Lodash isNumber function has an extra condition to check if value is number. I'm not sure why is that required and in what case it is not enough to use just typeof value == 'number'

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

.js

Lodash isNumber function has an extra condition to check if value is number. I'm not sure why is that required and in what case it is not enough to use just typeof value == 'number'

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

https://github./lodash/lodash/blob/aa1d7d870d9cf84842ee23ff485fd24abf0ed3d1/isNumber.js

Share Improve this question asked Jun 19, 2019 at 9:05 dlxeondlxeon 2,0101 gold badge13 silver badges16 bronze badges 3
  • 1 Maybe because typeof NaN is "number" ..? Uhh, the function doesn't seem to detect NaN at all. – Teemu Commented Jun 19, 2019 at 9:06
  • 1 _.isNumber(NaN) returns true – dlxeon Commented Jun 19, 2019 at 9:06
  • 1 Maybe if you set an objects prototype to Number.prototype – Sebastian Speitel Commented Jun 19, 2019 at 9:08
Add a ment  | 

2 Answers 2

Reset to default 9

From your link:

Checks if value is classified as a Number primitive or object.

var n = new Number(3);
console.log(typeof n); // "object"
console.log(_.isNumber(n)); // true

MDN - Number:

The Number JavaScript object is a wrapper object allowing you to work with numerical values. A Number object is created using the Number() constructor. A primitive type object number is created using the Number() function.

While the Number() function will create a number primitive, the Number() constructor will create a Number object:

typeof Number(0) // 'number'
typeof new Number(0) // 'object'

Lodash checks for both cases.

发布评论

评论列表(0)

  1. 暂无评论