为什么字符串到数字比较在Javascript中有效 [英] Why does string to number comparison work in Javascript

查看:128
本文介绍了为什么字符串到数字比较在Javascript中有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将来自HTML文本字段的值与整数进行比较。它按预期工作。
条件是 -

I am trying to compare a value coming from a HTML text field with integers. And it works as expected. Condition is -

x >= 1 && x <= 999;

其中 x 是文本字段的值。当值在1-999(含)之间时,条件返回 true ,否则 false
问题是,来自文本字段的值是字符串类型,我将它与整数类型进行比较。是否可以像这样进行比较,还是应该使用parseInt()将 x 转换为整数?

Where x is the value of text field. Condition returns true whenever value is between 1-999 (inclusive), else false. Problem is, that the value coming from the text field is of string type and I'm comparing it with integer types. Is it okay to have this comparison like this or should I use parseInt() to convert x to integer ?

推荐答案

因为JavaScript定义> = < = (和其他几个运算符)允许它们将操作数强制转换为不同类型。它只是运算符定义的一部分。

Because JavaScript defines >= and <= (and several other operators) in a way that allows them to coerce their operands to different types. It's just part of the definition of the operator.

< 的情况下,> < = > = ,血淋淋的细节是在规范的§11.8.5中列出。短版本是:如果两个操作数都是字符串(在必要时从对象强制后),它会进行字符串比较。否则,它会将操作数强制转换为数字并进行数字比较。

In the case of <, >, <=, and >=, the gory details are laid out in §11.8.5 of the specification. The short version is: If both operands are strings (after having been coerced from objects, if necessary), it does a string comparison. Otherwise, it coerces the operands to numbers and does a numeric comparison.

因此,您可以获得有趣的结果,例如90> 100(两者都是字符串,这是字符串比较)但是90< 100 (其中一个是数字,它是数字比较)。 : - )

Consequently, you get fun results, like that "90" > "100" (both are strings, it's a string comparison) but "90" < 100 (one of them is a number, it's a numeric comparison). :-)


这样的比较是否可以,或者我应该使用parseInt()将x转换为整数?

Is it okay to have this comparison like this or should I use parseInt() to convert x to integer ?

这是一个意见问题。有些人认为依靠隐性强制是完全没有问题的;其他人则认为不是。有一些客观的论点。例如,假设您依赖于隐式转换,它很好,因为您有这些数字常量,但后来您将 x 与从输入字段获得的另一个值进行比较。现在您要比较字符串,但代码看起来相同。但同样,这是一个意见问题,你应该自己做出选择。

That's a matter of opinion. Some people think it's totally fine to rely on the implicit coercion; others think it isn't. There are some objective arguments. For instance, suppose you relied on implicit conversion and it was fine because you had those numeric constants, but later you were comparing x to another value you got from an input field. Now you're comparing strings, but the code looks the same. But again, it's a matter of opinion and you should make your own choice.

如果你决定先显式转换为数字, parseInt 可能是也可能不是你想要的,做与隐式转换相同的事情。以下是选项的概述:

If you do decide to explicitly convert to numbers first, parseInt may or may not be what you want, and it doesn't do the same thing as the implicit conversion. Here's a rundown of options:


  • parseInt(str [,radix]) - 尽可能多地将字符串的开头转换为整数(整数),忽略末尾的额外字符。所以 parseInt(10x) 10 ;忽略 x 。支持可选的基数(数字基数)参数,所以 parseInt(15,16) 21 15 (十六进制)。如果没有基数,则假定为十进制,除非字符串以 0x (或 0X )开头,在这种情况下它会跳过那些并假定十六进制。 (某些浏览器用于将以 0 开头的字符串视为八进制;从未指定该行为,并且在ES5规范中[特别禁止] [2]。) 如果找不到可解析的数字,则返回 NaN

  • parseInt(str[, radix]) - Converts as much of the beginning of the string as it can into a whole (integer) number, ignoring extra characters at the end. So parseInt("10x") is 10; the x is ignored. Supports an optional radix (number base) argument, so parseInt("15", 16) is 21 (15 in hex). If there's no radix, assumes decimal unless the string starts with 0x (or 0X), in which case it skips those and assumes hex. (Some browsers used to treat strings starting with 0 as octal; that behavior was never specified, and was [specifically disallowed][2] in the ES5 specification.) Returns NaN if no parseable digits are found.

parseFloat(str) - 与 parseInt 类似,但是浮点数并且仅支持十进制。字符串上的额外字符将被忽略,因此 parseFloat(10.5x) 10.5 x 被忽略)。由于只支持十进制, parseFloat(0x15) 0 (因为解析以<$ c $结尾C> X )。如果找不到可解析的数字,则返回 NaN

parseFloat(str) - Like parseInt, but does floating-point numbers and only supports decimal. Again extra characters on the string are ignored, so parseFloat("10.5x") is 10.5 (the x is ignored). As only decimal is supported, parseFloat("0x15") is 0 (because parsing ends at the x). Returns NaN if no parseable digits are found.

一元 + ,例如 + str - (例如,隐式转换)使用浮点和JavaScript的标准数将整个字符串转换为数字符号(只是数字和小数点=十进制; 0x 前缀=十六进制; 0o 前缀=八进制[ES2015 +]; 一些实现扩展它以将前导 0 视为八进制,但不是严格模式。 +10x NaN 因为 x 是<强>不被忽略。 +10 10 +10.5 10.5 +0x15 21 +0o10 8 [ES2015 +]。有一个问题: + 0 ,而不是 NaN 正如您所料。

Unary +, e.g. +str - (E.g., implicit conversion) Converts the entire string to a number using floating point and JavaScript's standard number notation (just digits and a decimal point = decimal; 0x prefix = hex; 0o prefix = octal [ES2015+]; some implementations extend it to treat a leading 0 as octal, but not in strict mode). +"10x" is NaN because the x is not ignored. +"10" is 10, +"10.5" is 10.5, +"0x15" is 21, +"0o10" is 8 [ES2015+]. Has a gotcha: +"" is 0, not NaN as you might expect.

Number(str) - 完全像隐式转换(例如,像上面的一元 + ,但在某些实现上速度较慢。 (并非它可能很重要。)

Number(str) - Exactly like implicit conversion (e.g., like the unary + above), but slower on some implementations. (Not that it's likely to matter.)

按位或零,例如 str | 0 - 隐式转换,如 + str ,但它也将数字转换为32位整数(如果字符串无法转换为有效数字,则将 NaN 转换为 0

Bitwise OR with zero, e.g. str|0 - Implicit conversion, like +str, but then it also converts the number to a 32-bit integer (and converts NaN to 0 if the string cannot be converted to a valid number).

因此,如果可以忽略字符串上的额外位, parseInt parseFloat 没问题。 parseInt 对于指定基数非常方便。一元 + 对于确保考虑整个字符串非常有用。做出你的选择。 : - )

So if it's okay that extra bits on the string are ignored, parseInt or parseFloat are fine. parseInt is quite handy for specifying radix. Unary + is useful for ensuring the entire string is considered. Takes your choice. :-)

最后:如果您要转换为数字并想知道结果是否为 NaN ,你可能想要 if(convertedValue === NaN)。但无效,因为Rick 指出以下,涉及 NaN 的比较始终为false。相反,它是 if(isNaN(convertedValue))

And finally: If you're converting to number and want to know whether the result is NaN, you might be tempted to do if (convertedValue === NaN). But that won't work, because as Rick points out below, comparisons involving NaN are always false. Instead, it's if (isNaN(convertedValue)).

这篇关于为什么字符串到数字比较在Javascript中有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆