Underscore.js calling isNaN after isFinite functio

2019-04-11 17:36发布

In Underscore.js library, there is a function named isFinite returning 'true' if the value is a number. Considering that the built-in function isFinite of Javascript is already returning 'true' if the value passed as argument is a number, why we also need to call !isNaN(parseFloat(obj))?

// Is a given object a finite number?
  _.isFinite = function(obj) {
    return isFinite(obj) && !isNaN(parseFloat(obj));
  };

1条回答
祖国的老花朵
2楼-- · 2019-04-11 18:08

This covers the case of isFinite(""), isFinite(null) and isFinite(false) all returning true, because isFinite blindly converts its argument to a number and treats any of these like 0.

Starting with the numeric conversion...

Number("") // 0
Number(false) // 0
Number(null) // 0
Number(undefined) // NaN

... isFinite has some surprising results:

isFinite("") // true
isFinite(false) // true
isFinite(null) // true
isFinite(undefined) // false

Meanwhile, _.isFinite returns something more like you might expect, because parseFloat returns NaN for all these values

_.isFinite("") // false
_.isFinite(false) // false
_.isFinite(null) // false
_.isFinite(undefined) // false

Note that you can get the same explicit checking with Number.isFinite, which doesn't attempt to convert its argument (but which is less well supported across browsers):

Number.isFinite("") // false
Number.isFinite(false) // false
Number.isFinite(null) // false
Number.isFinite(undefined) // false
查看更多
登录 后发表回答