Var i = [0] in the for loop, then i ++ increases - why does it work?

In the book I'm reading (JavaScript and JQuery - Interactive Front End Development by Jon Duckett), an interesting error appears or (at least I think so) that does not stop the code from working:

for (var i = [0]; i < options.length; i++) { addEvent(options[i], 'click', radioChanged); } 

This is the part of the script that goes through all the switches in the form and attaches an event listener (it doesn't really matter what it does).

But...

  • Why am I initialized as an array?

  • Why does increment work?

  • Why does the whole cycle work?

Of course, if you replace var i = [0] with var i = 0, the code still works.

When you add some warnings to check the value of i in each iteration of the loop and type i, in the second iteration type I change from an object (after all, in the first iteration it is an array) to a number, This is a kind of implicit type conversion, with which I still have not came across (and google doesn't help much). Can anyone explain what is happening under the hood?

 for (var i = [0]; i < options.length; i++) { addEvent(options[i], 'click', radioChanged); alert(i); // --> 1 2 3 ... alert(type of i); // --> object number number ... } 
+7
javascript type-conversion for-loop
source share
1 answer

The specification says (ยง 11.3.1) that the ++ operator converts its operand to a number before incrementing:

  1. Let oldValue be ToNumber ( GetValue (lhs)).

When the object is called, the internal GetValue operation calls the toString() call, which for the array will be attached to its elements, returning '0' .

+8
source share

All Articles