我知道Lodash经常会向JavaScript中已经存在的函数添加一些额外的检查或细节,但是目前尚不清楚_.toNumber
的具体功能是我无法使用parseInt
获得的。
仅当Lodash提供现有JavaScript函数无法提供的好处,但在这种情况下我看不到任何好处时,我才愿意使用Lodash。
答案 0 :(得分:2)
_.toNumber
将给定的输入转换为数字(如果可能的话),否则返回NaN
。 parseInt
和parseFloat
方法也以相同的方式工作(尽管前者将仅返回整数),但是,它们在解析规则方面更为宽松。 _.toNumber的限制更大。
例如,使用相同的输入'5.2a'
,parseInt
将返回5
,parseFloat
将返回5.2
,而_.toNumber
将返回{ {1}}。前两个忽略第一个无法识别的字符之后的所有内容,并返回到该点为止所有已解析字符形成的数字。但是,如果遇到无法识别的字符,最后一个将返回NaN。
NaN
与_.toNumber
函数具有可比性,并且在功能上相同。
答案 1 :(得分:1)
我认为只看_.toNumber source会更好,这实际上可以回答您的问题:
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);
}
如您所见,与parseInt相比,它还有很多其他功能。具体来说:
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
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
因此,_.isNumber
的总结为您提供了更多expected / consistent
,而在解析包含数组,小数,虚假值和字符串。它将检查整个输入与safer
的对比,parseInt
仅关心第一个有效值,如您从上面的示例中看到的那样。它还可以更好地处理求反运算符(!
)等。
因此,总体而言,它确实与parseInt
相比有用途
注意:这里的陷阱是_.toNumber
和parseInt
都为NaN
返回undefined
,这考虑了{{1} }处理可能会返回_.toNumber
与0
的其余虚假值:
NaN