最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How is “for(const [[[[[a, b, c]]]]] in [0, 0]);” even valid? - Stack Overflow

matteradmin15PV0评论

Writing dumb code, I've just found something weird.

for(const [[[[[fancy, loop]]]]] in [0, 0]) {
  console.log(fancy, loop);
}

Writing dumb code, I've just found something weird.

for(const [[[[[fancy, loop]]]]] in [0, 0]) {
  console.log(fancy, loop);
}

// Chrome 70.0.3538.77 says:
// 0 undefined
// 1 undefined

It's like assigning 0 and 1 to [[[[[fancy, loop]]]]], which, is array destructurings taking place and supposed to throw an error, isn't it? Or not. It's just my thought getting me confused right now.

Could you please tell me how it is valid and works with no error? What am I missing?

Share Improve this question edited Nov 5, 2018 at 0:23 Константин Ван asked Nov 5, 2018 at 0:20 Константин ВанКонстантин Ван 14.7k8 gold badges74 silver badges86 bronze badges 5
  • @RobG Yeah, but, how could it destructure 0 and 1? – Константин Ван Commented Nov 5, 2018 at 0:25
  • 2 you can always throw the code into a transpiler to see what is happening – Bravo Commented Nov 5, 2018 at 0:25
  • 2 babeljs.io/repl/… – Bravo Commented Nov 5, 2018 at 0:26
  • 17 I guess you discovered a new question for javascript job interviews. ;-) – RobG Commented Nov 5, 2018 at 0:49
  • 4 ^ @RobG for anyone wondering, this should be taken as sarcasm – Pierre Arlaud Commented Nov 5, 2018 at 9:28
Add a comment  | 

2 Answers 2

Reset to default 26

It's not assigning 0 and 1 to [[[[[fancy, loop]]]]]. You're looping over the keys of [0, 0], because you used in instead of of, and those keys are strings.

The string "0" is an iterable whose sole element is "0". Assigning "0" to [[[[[fancy, loop]]]]] repeatedly unpacks "0" and gets "0", until eventually it gets down to

[fancy, loop] = "0"

at which point the final unpacking assigns "0" to fancy and undefined to loop.

You're using in instead of of so you're getting the properties of the array not the values. For this case you're getting the array indexes as strings (0, 1). You're basically destructuring a string with length of 1 every time. So you always get the first character of every iterated property

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far