how exactly do Javascript numeric comparison operators handle strings?

天涯浪子 提交于 2019-12-23 17:12:00

问题


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

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.


回答1:


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

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

'a' < 'b' and 'ab' < 'ac are both true.



来源:https://stackoverflow.com/questions/8177238/how-exactly-do-javascript-numeric-comparison-operators-handle-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!