using division operator (/) on strings in javascript

后端 未结 3 1446
野性不改
野性不改 2020-12-02 01:52

I realized that in javascript all 101/100, \"101\"/100, 101/\"100\" and \"101\"/\"100\" result in 1.01 (checked on Chrome, FF and IE11). But I cannot find a piece of documen

3条回答
  •  长情又很酷
    2020-12-02 02:53

    Type coercion is at play here. Quoting @Barmar's answer from What exactly is Type Coercion in Javascript?

    Type coercion means that when the operands of an operator are of different types, one of them will be converted to an "equivalent" value of the other operand's type.

    The reason for your observation is valid for other operations too -

    1 + "2" will give you "12"
    1 - "2" will give you -1 
    

    (because "-" operation on strings is not defined like division")

    In the case "101/100" the operation "/" will decide the coercion, since there is no operation defined on strings with that operator "/", but is there for "numbers".

    Using it is safe (at least in modern browsers) as long as you are clear how type coercion will play out in your operation.

提交回复
热议问题