【发布时间】:2019-11-17 06:04:58
【问题描述】:
我正在查看 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 arrays casting type-conversion boolean