lodash toNumber 和 parseInt 有什么区别?

Bra*_*ing 2 javascript parseint lodash

我知道 Lodash 经常为 JavaScript 中已经存在的函数添加一些额外的检查或细节,但不清楚_.toNumber我不会使用parseInt.

我更喜欢仅在 Lodash 提供现有 JavaScript 函数所不具备的好处时才使用它,但在这种情况下我看不到任何好处。

Akr*_*ion 10

我认为简单地查看_.toNumber 源要好得多,这实际上可以回答您的问题:

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);
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,与parseInt相比,它做了很多其他的事情。更具体:

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);
}
Run Code Online (Sandbox Code Playgroud)
console.log(_.toNumber(1),       parseInt(1))        // same 
console.log(_.toNumber('1'),     parseInt('1'))      // same  
console.log(_.toNumber('b'),     parseInt('b'))      // same  
console.log(_.toNumber({}),      parseInt({}))       // same 
console.log(_.toNumber(' 1 '),   parseInt(' 1 '))    // same
console.log(_.toNumber([1]),     parseInt([1]))      // same
console.log(_.toNumber(' 1a1 '), parseInt(' 1a1 '))  // NaN      1
console.log(_.toNumber([1,2]),   parseInt([1,2]))    // NaN      1
console.log(_.toNumber(false),   parseInt(false))    // 0        NaN
console.log(_.toNumber(!0),      parseInt(!0))       // 1        NaN
console.log(_.toNumber(!!0),     parseInt(!!0))      // 0        NaN
console.log(_.toNumber(5e-324),  parseInt(5e-324))   // 5e-324   5
console.log(_.toNumber(5.5),     parseInt(5.5))      // 5.5      5
console.log(_.toNumber(null),    parseInt(null))     // 0        NaN
console.log(_.toNumber(Infinity),parseInt(Infinity)) // Infinity NaN
Run Code Online (Sandbox Code Playgroud)

所以总结一下_.isNumber给你更多expected / consistentsafer当涉及到用数组、小数、假值和字符串解析输入时,我会争论结果。它将检查整个输入 vsparseInt只关心第一个有效值,如您在上面的示例中所见。它还可以更好地处理否定运算符 ( !) 等。

所以总的来说它确实有它的用途 vs parseInt

:什么是疑难杂症在这里的是,无论_.toNumberparseInt回报NaNundefined它考虑如何_.toNumber与falsy值的其余部分交易人会想到回报0VS NaN

console.log(_.toNumber(undefined), parseInt(undefined))  // NaN NaN
Run Code Online (Sandbox Code Playgroud)