首页 > 解决方案 > 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

标签: javascriptarrayscastingtype-conversionboolean

解决方案


+有两个操作数的是“加法运算符”,它可以根据其操作数进行数学加法或字符串加法(连接)。

当任何操作数+是对象时,JavaScript 引擎会将对象转换为基元。在您的情况下,数组是一个对象。将数组转换为原语会产生一个字符串(就好像您调用了他们的toString方法,基本上就是这样.join())。那么+操作员正在处理一个数字和一个字符串。当一操作数是字符串时,+将另一个操作数转换为字符串,这样就可以得到"2"结果。那是:

  • 2 + []变成
  • 2 + ""变成
  • "2" + ""这是
  • "2"

-有两个操作数的是“减法运算符”,它非常不同。它仅用于数学,没有任何字符串含义。这意味着它将参数转换为数字。将数组转换为数字包括首先将其转换为字符串,然后将字符串转换为数字。[]变成""转换为0。所以:

  • 2 - []变成
  • 2 - ""变成
  • 2 - 0这是
  • 2

推荐阅读