Why does string to number comparison work in Javascript

前端 未结 3 1298
滥情空心
滥情空心 2020-11-22 14:30

I am trying to compare a value coming from a HTML text field with integers. And it works as expected. Condition is -

x >= 1 && x <= 999;
         


        
3条回答
  •  渐次进展
    2020-11-22 15:06

    The MDN's docs on Comparision states that the operands are converted to a common type before comparing (with the operator you're using):

    The more commonly used abstract comparison (e.g. ==) converts the operands to the same Type before making the comparison. For relational abstract comparisons (e.g., <=), the operands are first converted to primitives, then to the same type, before comparison.

    You'd only need to apply parseInt() if you were using a strict comparision, that does not perform the auto casting before comparing.

提交回复
热议问题