![](/img/trans.png)
[英]Why is this expression in my Angular app displaying the literal text rather than the result of the evaluated expression?
[英]Why is typeof's result different than the evaluated result of the expression passed in?
如果将两个对象加在一起等于NaN (不是数字),从技术上讲是number类型,那么为什么将两个对象的类型加在一起会导致“字符串” ?
我将通过REPL表达这一点:
> {} + {}
> NaN
好。 将两个对象加在一起创建NaN
> typeof(NaN)
> "number"
好。 我们知道NaN的类型是“数字”
> typeof({} + {})
> "string"
等待。 这也不应该是“数字”吗?
我知道javascript的类型系统不那么令人满意,但是我对这里发生的事情感到困惑。 是否出于某种原因将类型从数字转换为字符串? 数字甚至是这里进行的类型转换的一部分吗? 还是我只是使用typeof错误?
{} + {}
是一个空块 ( {}
),然后是从对象到数字( +{}
)的类型转换。 它基本上读为
{} // empty block (a statement)
; // empty statement (just for clarity)
+{}; // expression statement (unary plus, object literal -> conversion to number)
但是,如果您使用typeof ({} + {})
,则{} + {}
将被视为表达式,在这种情况下, {}
只能是对象文字,而+
是串联运算符。
您也可以只使用分组运算符来强制将构造评估为表达式:
({} + {}) // expression statement (string concatenation with two objects)
另请参见为什么{} + {} NaN仅在客户端? 为什么不在Node.js中? 以及与[javascript] "{} + {}"
相关的其他问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.