Campbeln
Campbeln

Reputation: 2990

Is this for-in loop standards compliant?

I am attempting to limit the number of local variables exposed to an eval housed in a isolated closure to keep the scope as unpolluted as possible. But I also need to traverse a passed array, so I am doing something very similar to this:

var oObj = [{
    key: "",
    arr: {
      "one": 1,
      "two": 2,
      "three": 3
    }
}];

for (oObj[0].key in oObj[0].arr) {
    console.log(oObj[0].arr[oObj[0].key]);
}

In my actual code, oObj is passed into the closure'd function as the first argument (e.g. arguments[0]) so that the only local variable exposed to the function is arguments (which is exposed anyway).

This code works as expected, but jshint.com lists no fewer than 12 warnings for this code block.

So... am I pushing the envelop too far here or am I standards compliant? Can a for-in loop use an object.property for the key? JSHint doesn't seem to think so while everything I've tried seems happy with it.

Upvotes: 2

Views: 69

Answers (1)

tckmn
tckmn

Reputation: 59313

According to the ECMAScript standards, the syntax for a for-in loop is

IterationStatement : for ( LeftHandSideExpression in Expression ) Statement

And a LeftHandSideExpression can be a CallExpression, which furthermore can be a

CallExpression . IdentifierName

So, yes, according to the standards, it is a valid for-in loop.

But is it confusing? Yes. Why not just do something like this:

for (key in oObj[0].arr) {
    oObj[0].key = key;
    console.log(oObj[0].arr[key]);
}

Upvotes: 4

Related Questions