JavaScript Adding Booleans

后端 未结 3 596
眼角桃花
眼角桃花 2020-12-10 02:23
console.log(true+true); //2
console.log(typeof(true+true)); //number
console.log(isNaN(true+true)); //false

Why is adding together 2 boolean types

相关标签:
3条回答
  • 2020-12-10 02:39

    It works like that because that's how it's specified to work.

    EcmaScript standard specifies that unless either of the arguments is a string, the + operator is assumed to mean numeric addition and not string concatenation. Conversion to numeric values is explicitly mentioned:

    Return the result of applying the addition operation to ToNumber( lprim) and ToNumber(rprim).

    (where lprim and rprim are the primitive forms of the left-hand and the right-hand argument, respectively)

    EcmaScript also specifies the To Number conversion for booleans clearly:

    The result is 1 if the argument is true. The result is +0 if the argument is false.

    Hence, true + true effectively means 1 + 1, or 2.

    0 讨论(0)
  • 2020-12-10 02:48

    Javascript is a dynamically typed language, because you don't have to specify what type something is when you start, like bool x or int i. When it sees an operation that can't really be done, it will convert the operands to whatever they need to be so that they can have that operation done on them. This is known as type coercion. You can't add booleans, so Javascript will cast the booleans to something that it can add, something like a string or a number. In this case, it makes sense to cast it to a number since 1 is often used to represent true and 0 for false. So Javascript will cast the true's to 1s, and add them together

    0 讨论(0)
  • 2020-12-10 03:00

    Javascript is loosely typed, and it automatically converts things into other things to fit the situation. That's why you can do var x without defining it as an int or bool

    http://msdn.microsoft.com/en-us/library/6974wx4d(v=vs.94).aspx

    0 讨论(0)
提交回复
热议问题