为什么typeof的结果与传入的表达式的评估结果不同? [英] Why is typeof's result different than the evaluated result of the expression passed in?

查看:108
本文介绍了为什么typeof的结果与传入的表达式的评估结果不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果两个对象加在一起等于 NaN (非数字),技术上属于数字,那么为什么要获取该类型将两个对象加在一起会产生string

If two Objects added together equal NaN(not a number), which is technically of type number, then why does getting the type of two Objects added together result in "string"?

我将通过REPL表达:

> {} + {}

> NaN

ok。两个对象一起添加创建NaN

I will express this via the REPL:
> {} + {}
> NaN
ok. two objects added together creates NaN

> typeof(NaN)

> 数字

ok。我们知道NaN的类型是数字

> typeof(NaN)
> "number"
ok. we know that NaN's type is "number"

> typeof({} + {})

> string

等等。难道这也不应该是数字吗?

> typeof({} + {})
> "string"
wait. shouldn't this have been "number" also?

我知道javascript有一个不那么令人向往的类型系统,但我很困惑这里发生了什么。由于某种原因,类型是从数字转换为字符串吗?数字甚至是转换类型转换的一部分吗?或者我只是使用typeof错误?

I'm aware that javascript has a less then desireable type system, but I'm confused as to what's happening here. Is the type being converted from number to string for some reason? Is number even a part of the type converting that goes on here? Or am I just using typeof wrong?

推荐答案

{} + {} 是一个空 {} ),然后是从对象到数字的类型转换( + {} )。它基本上读为

{} + {} is an empty block ({}) followed by a type conversion from object to number (+{}). It basically reads as

{} // empty block (a statement)
;  // empty statement (just for clarity)
+{}; // expression statement (unary plus, object literal -> conversion to number)

但是如果你使用 typeof({} + {}),然后 {} + {} 将被评估为表达式在这种情况下, {} 只能是对象文字, + 是连接运算符。

However if you use typeof ({} + {}), then {} + {} will be evaluated as expression in which case both {} can only be object literals and the + is the concatenation operator.

您也可以使用分组运算符强制将结构计算为表达式:

You can also just use the grouping operator to force the construct to be evaluated as expression:

({} + {}) // expression statement (string concatenation with two objects)






另请参见为什么{} + {}仅在客户端为NaN ?为什么不在Node.js?和其他与 [javascript]{} + {}


See also Why {} + {} is NaN only on the client side? Why not in Node.js? and other questions related to [javascript] "{} + {}".

这篇关于为什么typeof的结果与传入的表达式的评估结果不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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