【问题标题】:What is the explanation for typeof a where var a = 2 + [] is string?typeof a where var a = 2 + [] is string 的解释是什么?
【发布时间】: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


【解决方案1】:

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

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

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

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

  • 2 - [] 变为
  • 2 - "" 变成了
  • 2 - 0
  • 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2021-10-13
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    相关资源
    最近更新 更多