Search code examples
javascriptfor-loopimplicitevaluate

how to evaluate implicit (unnamed) variable in for loop?


The following works fine in JS:

function GetArray() { return ["x","y","z"]; }
var tmp = GetArray();
var s = "";
for (var i in tmp) { s += i+" = "+tmp[i]+"\n"; }
alert(s);

Which gives:

0 = x
1 = y
2 = z

Now instead of storing GetArray()'s result in a temporary variable, is there also a way to do this by directly evaluating GetArray in the for (...) part?

I mean like this:

for (var i in GetArray()) { /* ??? */ }

Except in this case I don't know how to get element [i] of the array, as there is no explicit variable name to refer to?

Obviously I don't do GetArray()[i] as then GetArray is reprocessed every for-step, which is inefficient and its result may even change (not in this simplified example, but in general).

In PHP there is the concept of foreach(SomeExpression() as $index => $value), is there an equivalent in JS?


Solution

  • arr.forEach(callback[, thisArg])
    

    Gives you:

    function callback(element, index, array) {
        // ...
    }
    

    BUT the best answer including all caveats can be found here: https://stackoverflow.com/a/9329476/675561