Javascript 什么';lodash toNumber和parseInt的区别是什么?

Javascript 什么';lodash toNumber和parseInt的区别是什么?,javascript,lodash,parseint,Javascript,Lodash,Parseint,我知道Lodash经常会对JavaScript中已经存在的函数添加一些额外的检查或细节,但不清楚\uu.toNumber具体做了什么,这是parseInt无法做到的 我更愿意只在Lodash提供了现有JavaScript函数所没有的优点时才使用它,但在这种情况下我看不到任何好处。\uuUnumber如果可以将给定的输入转换为数字,否则返回NaN。parseInt和parseFloat方法也以同样的方式工作(虽然前者只返回整数),但是它们的解析规则要宽松得多。toNumber的限制性要大得多 例如

我知道Lodash经常会对JavaScript中已经存在的函数添加一些额外的检查或细节,但不清楚
\uu.toNumber
具体做了什么,这是
parseInt
无法做到的


我更愿意只在Lodash提供了现有JavaScript函数所没有的优点时才使用它,但在这种情况下我看不到任何好处。

\uuUnumber
如果可以将给定的输入转换为数字,否则返回
NaN
parseInt
parseFloat
方法也以同样的方式工作(虽然前者只返回整数),但是它们的解析规则要宽松得多。toNumber的限制性要大得多

例如,使用相同的输入
'5.2a'
parseInt
将返回
5
parseFloat
将返回
5.2
,而
toNumber
将返回
NaN
。前两个函数忽略第一个未识别字符之后的所有内容,并返回在此之前所有已解析字符形成的数字。但是,如果遇到无法识别的字符,则最后一个返回NaN


在功能上与
Number
功能类似。

我认为最好只看一下,这将实际回答您的问题:

function toNumber(value) {
  if (typeof value == 'number') {
    return value;
  }
  if (isSymbol(value)) {
    return NAN;
  }
  if (isObject(value)) {
    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
    value = isObject(other) ? (other + '') : other;
  }
  if (typeof value != 'string') {
    return value === 0 ? value : +value;
  }
  value = value.replace(reTrim, '');
  var isBinary = reIsBinary.test(value);
  return (isBinary || reIsOctal.test(value))
    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
    : (reIsBadHex.test(value) ? NAN : +value);
}
正如你所看到的,相比之下,它做了很多其他的事情。更具体地说:

console.log(u.toNumber(1),parseInt(1))//相同
console.log(u.toNumber('1'),parseInt('1'))//相同
console.log(u.toNumber('b')、parseInt('b'))//相同
console.log({.toNumber({}),parseInt({}))//相同
console.log(u.toNumber('1')、parseInt('1'))//相同
console.log(u.toNumber([1])、parseInt([1])//相同
console.log(u.toNumber('1a1')、parseInt('1a1'))//NaN 1
console.log(u.toNumber([1,2]),parseInt([1,2])//NaN 1
console.log(u.toNumber(false),parseInt(false))//0
console.log(u.toNumber(!0),parseInt(!0))//1 NaN
console.log(u.toNumber(!!0),parseInt(!!0))//0 NaN
console.log(u.toNumber(5e-324),parseInt(5e-324))//5e-324 5
console.log(u.toNumber(5.5),parseInt(5.5))//5.5
console.log(u.toNumber(null),parseInt(null))//0 NaN
console.log(u.toNumber(Infinity),parseInt(Infinity))//Infinity NaN

说得好,我应该先检查一下源代码。我将在以后的lodash问题中这样做,因为我总是这样想。我想建议对上述答案进行更正。我认为如果说lodash toNumber提供了更多的预期结果,可能会产生误导。请使用以下值扩展示例:10%100$$100或任何其他货币字符。parseInt和parseFloat都会像预期的那样处理它们,其中toNumber返回NaN。