gpt4 book ai didi

javascript - + 运算符与 parseFloat

转载 作者:数据小太阳 更新时间:2023-10-29 06:01:14 26 4
gpt4 key购买 nike

Example 1 knockout extenders 页面的描述了一种舍入用户输入并确保它只是数字的方法。

它工作得很好,但是通过查看源代码他们做了一件我不明白的奇怪的事情,那就是在第 8 行他们这样做:

parseFloat(+newValue)

newValue 是一个字符串。

当我最初问这个问题时,我不知道 + 做了什么 - 更进一步 poking和一个 link to a different MDN page从我得到的一个最初的答案表明它是一个等价于 number(str) 的一元运算符并且 +strparseFloat(str )(以字母字符结尾的字符串的处理和十六进制的解释似乎是头条新闻)。

我仍然不明白为什么在这种情况下 + 需要包装在 parseFloat 中,尽管我开始认为这可能是一个错字......

最佳答案

parseFloat 引用 MDN 文档:

parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed.

<罢工>使用 [unary plus operator][2] 您可以确定 `parseFloat` 对 `Number` 进行操作,这仅在您想要对结果更严格但仍想使用 `parseFloat` 时才有用
parseFloat('0.32abcd') // -> 0.32
parseFloat(+'0.32abcd') // -> NaN
**更新:**

在深入研究文档并运行一些测试后,似乎没有理由使用 parseFloat除了解析可能包含带有非数字尾迹的数字的字符串外,eq:

parseFloat('31.5 miles') // -> 31.5
parseFloat('12.75em') // -> 12.75

对于您的字符串包含数字 + 的任何其他情况是一种最快且首选的方式(引用 MDN docs for unary plus operator ):

unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number.

参见 parseFloat versus unary test case它有多快。

上一个链接断开所以 here is the new test这表明一元的速度有多快。

关于javascript - + 运算符与 parseFloat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33394852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com