问题描述
[] + [],[] + {},{} + [],{} + {}的值是多少?怎么样?
What are the values of []+[], []+{}, {}+[], {}+{}? And How?
我的控制台日志
>{} + {}
>NaN
>[] + []
>''
>{} + []
>0
>[] + {}
>[Object object]
此外
>var a = [] + {}
>a
>[Object object]
>var b = {} + []
>b
>[Object object]
分配值如何变化?
SRC:
推荐答案
{的区别} + []
就是当你执行赋值时,它会在表达式上下文中解析,但是当你自己键入它时它会被解析为一个语句
The difference for the {} + []
is that when you do an assignment it is parsed in an expression context but when you type it by itself it is parsed as a statement
var b = /*an expression*/
使用匿名函数时可以看到这种区别
This distinction is visible when using anonymous functions
//expression
var f = function(){}; //allowed
//statement
function(){}; //not allowed. function statements need a name.
所以在表达式上下文中,我们添加 {}
(空对象)和 []
(空列表),其中包含。由于, {}
转换为字符串和 []
转换为,其串联也是[object Object]。
So in the expression context, we add {}
(empty object) and []
(empty list) with the binary +
operator. Due to the type conversion rules, {}
is converted to the string "[object Object]" and []
is converted to the empty string, the concatenation of which is "[object Object]" too.
//parenthesis force an expression
({} + "hello") //"[object Object]hello"
({} + []) //"[object Object]"
({} + [1]) //"[object Object]1"
({} + [1,2]) //"[object Object]1,2"
同时,当我们删除括号时, {}
被解析为空块语句。出于实际目的,它就好像我们已完全承诺它一样,留下一个在列表上行动。这会将其转换为数字。
Meanwhile, when we remove the parenthesis, the {}
is parsed as an empty block statement. For pratical purposes it works as if we had commited it entirely, leaving an unary +
operator to act on the list. This converts it to a number.
+[] // 0
{} + [] // 0
+{} // NaN
{} + {} // NaN
{} +"17"// 17
虽然能够从语句中获取值(而不仅仅是表达式)似乎很奇怪,但是Javascript标准,确实 语句的值。在我们的例子中,我们的程序是两个源元素的列表,其 ,。
While it might seem weird to be able to get a value from a statement (instead of only from expressions), the Javascript standard, does specify a value for a statement. In our case, our program is a list of two source elements, whose value is given by the last statement, an expression statement.
查看操作中的语句完成值的方法是通过eval:
A way to see the statement completion value in action is via eval:
eval("{}") //undefined
eval("1") //1
eval("1;2") //2
这篇关于什么是javascript中的[] + []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!