javascript - typeof a where var a = 2 + [] is string 的解释是什么?
问题描述
我正在查看 a 的类型,其中 var a = 2 + []。我希望答案是数字类型的 2,但我得到的是字符串类型的“2”。但是,当我评估 var b = 2 - [] 时,我得到的值为 2 类型的数字。有人可以帮助我理解这种行为。
const arr = [];
const a = 2 + arr;
console.log(a); // '2'
console.log(typeof a) // string
const b = 2 - arr;
console.log(b) // 2
console.log(typeof b); // number
//I expected the value a to be 2 of type
//number just as b
//If I toggle the boolean value of arr,
//both a and b evaluates to 2 of
//type number
解决方案
+
有两个操作数的是“加法运算符”,它可以根据其操作数进行数学加法或字符串加法(连接)。
当任何操作数+
是对象时,JavaScript 引擎会将对象转换为基元。在您的情况下,数组是一个对象。将数组转换为原语会产生一个字符串(就好像您调用了他们的toString
方法,基本上就是这样.join()
)。那么+
操作员正在处理一个数字和一个字符串。当任一操作数是字符串时,+
将另一个操作数转换为字符串,这样就可以得到"2"
结果。那是:
2 + []
变成2 + ""
变成"2" + ""
这是"2"
-
有两个操作数的是“减法运算符”,它非常不同。它仅用于数学,没有任何字符串含义。这意味着它将参数转换为数字。将数组转换为数字包括首先将其转换为字符串,然后将字符串转换为数字。[]
变成""
转换为0
。所以:
2 - []
变成2 - ""
变成2 - 0
这是2
推荐阅读
- angular - 提交隐藏和非隐藏表单字段角度
- android - 如何将公历日期转换为伊斯兰(回历)日期?
- python - 使用 NLP 和 ML 在 Google 上自动搜索公司信息(并购)
- python - 使用 Python 脚本为远程网页生成 Selenium 屏幕截图 - 出现 about:neterror 错误
- python - 编写一个 for 循环来删除标点符号
- google-chrome - 如何让 chrome devtools 识别 moment.js
- java - 难以找到与 JavaScript 正则表达式等效的 Java 正则表达式
- android - 如何清理僵尸进程
- python - 如何在 Python 中压缩文件夹?
- java - 如何仅使用文件名获取 Java File AbsolutePath()?