本文介绍了+ operator vs parseFloat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

淘汰扩展器页面的描述了一种舍入用户输入并确保用户输入的方法它只是数字。

Example 1 of the knockout extenders page describes a way of rounding user input and making sure it is only numeric.

它的效果很好,但是从源头看,它们做了一件我不理解的特殊事情,就是在第8行他们这样做:

It works great, but looking through the source they do a peculiar thing that i don't understand, that is on line 8 they do this:

parseFloat(+newValue)

newValue 是一个字符串。

当我最初问这个问题时,我没有'知道 + 做了什么 - 进一步和来自我得到的一个初始答案,表明它是一个等同于 number(str)的一元运算符,并且有一个在 + str parseFloat(str)之间存在一些差异(处理以字母字符结尾的字符串和十六进制的解释似乎成为标题)。

When i initially asked this question I didn't know what + did - some further poking and a link to a different MDN page from one of the initial answers I got indicate it is a unary operator equivalent to number(str) and that there are some differences between +str and parseFloat(str) (treatment of strings ending in alpha characters and interpretation of hex seem to be the headlines).

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

I still don't understand why the + in this case needed to be wrapped in the parseFloat although I am starting to think it might be a typo...

推荐答案

引用用于:


更新:

经过一些挖掘文档并运行一些测试后,似乎没有理由使用 parseFloat 而不是解析字符串可以包含带数字的非数字路径的数字,例如:

After a bit of digging in docs and running some tests, seems there is no reason to use parseFloat other than parsing strings that may contain numbers with non numeric trails to number, eq:

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

对于您的字符串包含数字 + 最快且首选的方式(引用):

For any other cases where your string contains number + is a fastest and prefered way (citing MDN docs for unary plus operator):

请参阅的速度有多快。

这篇关于+ operator vs parseFloat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 09:38