JavaScript添加布尔值 [英] JavaScript Adding Booleans

查看:45
本文介绍了JavaScript添加布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

console.log(true+true); //2
console.log(typeof(true+true)); //number
console.log(isNaN(true+true)); //false

为什么将2个布尔类型加在一起会产生数字?我有点理解,如果它们不相等(1/0(二进制?)),尝试对布尔类型执行算术将很尴尬,但是我找不到这种逻辑背后的原因.

Why is adding together 2 boolean types yielding a number? I kind of understand that if they didn't equal (1/0 (binary?)) it would be awkward to try to perform arithmetic on a boolean type, but I can't find the reasoning behind this logic.

推荐答案

它的工作原理是这样的,因为它是指定工作的方式.

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

EcmaScript标准指定,除非两个自变量中的任何一个为字符串,否则 + 运算符均假定为数字加法,而不是字符串串联.明确提到转换为数值:

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:

返回对ToNumber(lprim)和ToNumber(rprim)应用加法运算的结果.

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

(其中 lprim rprim 分别是左手参数和右手参数的原始形式)

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

EcmaScript还为布尔值明确指定了 To Number 转换:

EcmaScript also specifies the To Number conversion for booleans clearly:

如果参数为true,则结果为1.如果参数为false,则结果为+0.

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

因此, true + true 实际上表示 1 + 1 2 .

这篇关于JavaScript添加布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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