Javascript数字比较运算符如何精确地处理字符串? [英] how exactly do Javascript numeric comparison operators handle strings?

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

问题描述

var i = ['5000','35000'];
alert((i[0] < i[1])?'well duh!':'fuzzy math?');
alert((Number(i[0]) < Number(i[1]))?'well duh!':'fuzzy math?');

这里发生了什么?在第一个警报中,文本字符串 5000的评估结果为小于 35000。我以为Javascript在对字符串进行数字比较时使用了Number(),但显然并非如此。只是很好奇Javascript在默认情况下如何精确地对数字字符串进行数字比较。

What's happening here? In the first alert, the text string "5000" evaluates as not less than "35000". I assumed Javascript used Number() when numerically comparing strings, but apparently that's not the case. Just curious how exactly Javascript handles numerically comparing the strings of numbers by default.

推荐答案

Javascript通过字符值比较字符串,无论字符串是否看起来像还是不像数字。

Javascript compares strings by character value, whether the strings look like numbers or not.

您可以在规范,第11.8.5节,第4点。

You can see this in the spec, section 11.8.5, point 4.

'a'< ‘b’‘ab’< ‘ac 都是真的。

这篇关于Javascript数字比较运算符如何精确地处理字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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