使用数组添加对象的问题 [英] Problems with adding object with array
问题描述
受此视频的启发,我使用<$测试进一步 c $ c> {} + [] 。
Inspired by this video, I tested further with {}+[]
.
测试1:
typeof {}+[] //"object"
好的,所以 {} + []
是一个对象
。
测试2:
var crazy = {}+[];
typeof crazy //"string"
什么?没有 {} + []
是一个对象
?为什么现在字符串
?
What? Didn't {}+[]
is an object
? Why is it a string
now?
测试3:
console.log({}+[])
我得到了什么:
所以它是数字
!...不?
所以实际上 {} + []
??
So what actually is the type of {}+[]
??
对于那些说 {} + []
的人来说空字符串:
To people who say {}+[]
is a empty string:
{}+[] === "" //false
({}+[]) === "" //false
({};+[]) === "" //SyntaxError
({}+[]).length //15
JavaScript很难理解......
JavaScript is so hard to understand...
推荐答案
{} + []
的类型可能因环境而异。
Type of {}+[]
may vary depending on the context.
-
typeof {} + [] //object
根据运算符优先级,在这种情况下typeof {}
评估ates toobject,+ []
添加一个空字符串(数组被强制转换为字符串)因此结果是object。
你可能会想到检查typeof({} + [])
(你的第二种情况)。
typeof {}+[] //"object"
As per operators precedence in this casetypeof {}
evaluates to "object",+[]
adds an empty string(array is coerced to string) therefore result is "object".
You could think of checkingtypeof ({}+[])
(your second case).
var crazy = {} + [];
typeof crazy //string
在这种情况下,您要添加对象和数组 - 它们都强制为字符串,因此 typeof
返回string。
var crazy = {}+[];
typeof crazy //"string"
In this case you are adding object and array - they both coerce to string, therefore typeof
returns "string".
{} + []
这被解释为一个空的代码块,一元加和空数组。
第一部分什么都不做,数组转换为逗号分隔的字符串(空数组为空数组),然后转换为数字(空字符串转换为0),因此 0
。
更新
-
{} + [] ===// false
见#3,{}
被解释为一个块,左边是0
。
比较{} + [] === 0 // true
。
{}+[] === "" //false
see #3,{}
is interpreted as a block, you are getting0
on the left.
Compare{}+[] === 0 // true
.
({} + [])===// false
见#1, {}
被解释为对象文字。当尝试添加数组和对象时,它们都转换为字符串,[object Object]
表示对象,空字符串表示数组。因此,你在左边得到[object Object]
。
比较({} + [])= ==[object Object]// true
。
({}+[]) === "" //false
see #1, {}
is interpreted as an object literal. When trying to add array and object, they both convert to string, "[object Object]"
for object and empty string for array. Hence, you are getting "[object Object]"
on the left.
Compare ({}+[]) === "[object Object]" // true
.
({}; + [] )===//语法错误
我想,这个是不言自明的:)
({};+[]) === "" //SyntaxError
I guess, this one is self-explanatory :)
({} + [])。length // 15
15正好是的长度[object Object ]
,见上文。
这篇关于使用数组添加对象的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!