Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

javascript - Problems with adding object with array

Inspired by this video, I tested further with {}+[].

Test 1:

typeof {}+[]  //"object"

Okay, so {}+[] is an object.

Test 2:

var crazy = {}+[];
typeof crazy  //"string"

What? Didn't {}+[] is an object? Why is it a string now?

Test 3:

console.log({}+[])

What I got:

enter image description here

So it is a number!... No?

So what actually is the type of {}+[]??

UPDATED

To people who say {}+[] is a empty string:

{}+[] === ""     //false
({}+[]) === ""   //false
({};+[]) === ""  //SyntaxError
({}+[]).length   //15

JavaScript is so hard to understand...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Type of {}+[] may vary depending on the context.

  1. typeof {}+[] //"object"
    As per operators precedence in this case typeof {} evaluates to "object", +[] adds an empty string(array is coerced to string) therefore result is "object".
    You could think of checking typeof ({}+[]) (your second case).

  2. var crazy = {}+[]; typeof crazy //"string"
    In this case you are adding object and array - they both coerce to string, therefore typeof returns "string".

  3. {}+[]
    This is interpreted as an empty block of code, unary plus and empty array. First part does nothing, array is converted to a comma-separated string of it's elements(empty string for empty array), then to a number(empty string is converted to 0), hence 0.

UPDATED

  • {}+[] === "" //false
    see #3, {} is interpreted as a block, you are getting 0 on the left.
    Compare {}+[] === 0 // 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 is exactly the length of "[object Object]", see above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...