javascript 如何将两个字符串值作为整数进行比较?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12598413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:37:45  来源:igfitidea点击:

How to compare two string values as integers?

javascript

提问by Anjana

I am converting and comparing two string values using

我正在使用

if (parseInt(x)!=parseInt(y)) {

The problem is if values are x="9"and y="09"the test returns false.

问题是如果值是x="9"并且y="09"测试返回false

How can I get fix this ?

我怎样才能解决这个问题?

回答by Denys Séguret

Use this :

用这个 :

if(parseInt(x, 10)!=parseInt(y, 10))

If you don't precise the radix, "09" is parsed as octal (this gives 0).

如果您不精确基数,“09”将被解析为八进制(这给出 0)。

MDN documentation about parseInt

关于 parseInt 的 MDN 文档

Note that you shouldn't even rely on this interpretation when working with octal representations :

请注意,在使用八进制表示时,您甚至不应该依赖这种解释:

ECMAScript 5 Removes Octal Interpretation

The ECMAScript 5 specification of the function parseInt no longer allows implementations to treat Strings beginning with a 0 character as octal values. ECMAScript 5 states:

The parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading white space in string is ignored. If radix is undefined or 0, it is assumed to be 10 except when the number begins with the character pairs 0x or 0X, in which case a radix of 16 is assumed. If radix is 16, number may also optionally begin with the character pairs 0x or 0X.

This differs from ECMAScript 3, which discouraged but allowed octal interpretation.

Since many implementations have not adopted this behavior as of 2011, and because older browsers must be supported, always specify a radix.

ECMAScript 5 移除八进制解释

函数 parseInt 的 ECMAScript 5 规范不再允许实现将以 0 字符开头的字符串视为八进制值。ECMAScript 5 声明:

parseInt 函数产生一个整数值,由根据指定基数解释字符串参数的内容决定。字符串中的前导空格将被忽略。如果基数未定义或为 0,则假定为 10,除非数字以字符对 0x 或 0X 开头,在这种情况下假定基数为 16。如果基数为 16,数字也可以选择以字符对 0x 或 0X 开头。

这与 ECMAScript 3 不同,后者不鼓励但允许八进制解释。

由于截至 2011 年许多实现尚未采用此行为,并且必须支持旧浏览器,因此请始终指定基数。

Simply :

简单地 :

always specify a radix

总是指定一个基数

回答by plus-

You need to set the radix explicitelly to 10 otherwise it assume it is 8 (javascript bad parts):

您需要将基数显式设置为 10,否则它假定为 8(javascript 坏部分):

parseInt(x,10)

http://www.w3schools.com/jsref/jsref_parseint.asp

http://www.w3schools.com/jsref/jsref_parseint.asp

If the string begins with "0", the radix is 8 (octal). This feature is deprecated

如果字符串以“0”开头,则基数为 8(八进制)。此功能已弃用