Javascript 字符串/整数比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5630123/
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-08-23 18:09:14  来源:igfitidea点击:

Javascript string/integer comparisons

javascripthtml

提问by Ronan Sharp

I store some parameters client-side in HTML and then need to compare them as integers. Unfortunately I have come across a serious bug that I cannot explain. The bug seems to be that my JS reads parameters as strings rather than integers, causing my integer comparisons to fail.

我将一些参数客户端存储在 HTML 中,然后需要将它们作为整数进行比较。不幸的是,我遇到了一个我无法解释的严重错误。错误似乎是我的 JS 将参数读取为字符串而不是整数,导致我的整数比较失败。

I have generated a small example of the error, which I also can't explain. The following returns 'true' when run:

我已经生成了一个错误的小例子,我也无法解释。运行时以下返回“true”:

javascript:alert("2">"10")

回答by icktoofay

Parse the string into an integer using parseInt:

使用parseInt以下命令将字符串解析为整数:

javascript:alert(parseInt("2", 10)>parseInt("10", 10))

回答by RobG

Checking that strings are integers is separate to comparing if one is greater or lesser than another. You should always compare number with number and string with string as the algorithm for dealing with mixed types not easy to remember.

检查字符串是否为整数与比较一个大于或小于另一个是分开的。您应该始终将数字与数字和字符串与字符串进行比较,作为处理不易记住的混合类型的算法。

'00100' < '1' // true

as they are both strings so only the first zero of '00100' is compared to '1' and because it's charCode is lower, it evaluates as lower.

因为它们都是字符串,所以只有 '00100' 的第一个零与 '1' 进行比较,并且因为它的 charCode 较低,所以它评估为较低。

However:

然而:

'00100' < 1 // false

as the RHS is a number, the LHS is converted to number before the comparision.

由于 RHS 是一个数字,LHS 在比较之前被转换为数字。

A simple integer check is:

一个简单的整数检查是:

function isInt(n) {
  return /^[+-]?\d+$/.test(n);
}

It doesn't matter if n is a number or integer, it will be converted to a string before the test.

n 是数字还是整数都没有关系,在测试之前它会被转换为字符串。

If you really care about performance, then:

如果你真的关心性能,那么:

var isInt = (function() {
  var re = /^[+-]?\d+$/;

  return function(n) {
    return re.test(n);
  }
}());

Noting that numbers like 1.0 will return false. If you want to count such numbers as integers too, then:

请注意,像 1.0 这样的数字将返回 false。如果您也想将此类数字计算为整数,则:

var isInt = (function() {
  var re = /^[+-]?\d+$/;
  var re2 = /\.0+$/;

  return function(n) {
    return re.test((''+ n).replace(re2,''));
  }
}());

Once that test is passed, converting to number for comparison can use a number of methods. I don't like parseInt()because it will truncate floats to make them look like ints, so all the following will be "equal":

一旦该测试通过,转换为数字进行比较可以使用多种方法。我不喜欢parseInt()因为它会截断浮点数使它们看起来像整数,因此以下所有内容都将“相等”:

parseInt(2.9) == parseInt('002',10) == parseInt('2wewe')

and so on.

等等。

Once numbers are tested as integers, you can use the unary + operator to convert them to numbers in the comparision:

一旦数字被测试为整数,您可以使用一元 + 运算符将它们转换为比较中的数字:

if (isInt(a) && isInt(b)) {
  if (+a < +b) {
    // a and b are integers and a is less than b
  }
}

Other methods are:

其他方法是:

Number(a); // liked by some because it's clear what is happening
a * 1      // Not really obvious but it works, I don't like it

回答by Cody

Comparing Numbers to String Equivalents Without Using parseInt

在不使用的情况下将数字与字符串等价物进行比较 parseInt

console.log(Number('2') > Number('10'));
console.log( ('2'/1) > ('10'/1) );

var item = { id: 998 }, id = '998';
var isEqual = (item.id.toString() === id.toString());
isEqual;

回答by Senthil

use parseIntand compare like below:

使用parseInt和比较如下:

javascript:alert(parseInt("2")>parseInt("10"))

回答by Bimlendu Kumar

Always remember when we compare two strings. the comparison happens on chacracter basis. so '2' > '12' is true because the comparison will happen as '2' > '1' and in alphabetical way '2' is always greater than '1' as unicode. SO it will comeout true. I hope this helps.

永远记住当我们比较两个字符串时。比较是基于字符进行的。所以 '2' > '12' 是真的,因为比较将发生为 '2' > '1' 并且按字母顺序,'2' 总是大于 '1' 作为 unicode。所以它会成真。我希望这有帮助。

回答by Steve

The alert() wants to display a string, so it will interpret "2">"10" as a string.

alert() 想要显示一个字符串,所以它会将 "2">"10" 解释为一个字符串。

Use the following:

使用以下内容:

var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);

var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);

回答by OlegDovger

The answer is simple. Just divide string by 1. Examples:

答案很简单。只需将字符串除以 1。示例:

"2" > "10"   - true

but

"2"/1 > "10"/1 - false

Also you can check if string value really is number:

您也可以检查字符串值是否真的是数字:

!isNaN("1"/1) - true (number)
!isNaN("1a"/1) - false (string)
!isNaN("01"/1) - true (number)
!isNaN(" 1"/1) - true (number)
!isNaN(" 1abc"/1) - false (string)

But

!isNaN(""/1) - true (but string)

Solution

解决方案

number !== "" && !isNaN(number/1)