Javascript字符串/整数比较 [英] Javascript string/integer comparisons

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

问题描述

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



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

  javascript:alert(2>10)


解决方案

使用 parseInt

< pre $ javascript:alert(parseInt(2,10)> parseInt(10,10))


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.

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

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

解决方案

Parse the string into an integer using parseInt:

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

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

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