Question

In the Re-Introduction to Javascript, the syntax

for (var i = 0, item; item = a[i++];)

is explained as the middle "item" being a conditional test for truthtiness/falsiness. However, I had assumed the syntax to be (start; condition test; control factor) with semi-colons between each segment. Here, the syntax is unfamiliar to me in the form (start, condition test; control factor;) with a comma in the middle and semicolon at the very end. Is it equivalent to

for (var i = 0; item; item = a[i++])

?

If so, why write it using comma and semicolon at the end?

Était-ce utile?

La solution

In that expression, we have

  • initialization = var i = 0, item -- this declares two variables, and assigns one of them.
  • condition = item = a[i++] -- this performs an assignment, and tests the result of the assignment
  • control factor = nothing -- the increment of i was done as part of the condition, so nothing is needed here

A for-loop is essentially equivalent to the following:

initialization;
while (condition) {
    body;
    control factor;
}

So when we substitute from your loop, we get:

var i = 0, item;
while (item = a[i++]) {
    // body that you didn't show
}

An assignment's value is the value that was assigned, so the condition is whether a[i] was truthy. No control factor is needed because a[i++] returns the value of a[i] and also increments i at the same time.

A more typical way to write this loop would be:

for (var i = 0; a[i]; i++) {
    var item = a[i];
    // body that you didn't show
}

The author was just showing how you can combine many pieces of this.

Autres conseils

The format hasn't changed. It's simply declaring the var item. So, it is declaring two variables in the start section. The truthiness test is item = a[i++]; and the control factor is nothing.

for (;;) statement

Is a valid for statement. You don't HAVE to put anything in any of the sections.

item = a[i++] evaluates to true so long as item evaluates to true. The truthiness is done on the left-hand side of the assignment. That will depend on it's data type, but for an int, this could be any value besides 0 for example.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top