2

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?

Renato Gama
  • 16,431
  • 12
  • 58
  • 92
RocketNuts
  • 9,958
  • 11
  • 47
  • 88
  • If you only care about extra lines of code, then you can always do `for (var i in (tmp = GetArray())) { ... }` – Aleks G Oct 14 '14 at 11:05
  • or you use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – john Smith Oct 14 '14 at 11:06
  • the next version of javascript is going to have a for...of that would solve this same problem more elegantly.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of – Prabhu Murthy Oct 14 '14 at 11:12
  • Thanks to all, works like a charm! And the topic mentioned by Graeme Wicksted really covers it well. – RocketNuts Oct 14 '14 at 11:23

3 Answers3

2

You could use forEach:

var s = "";
GetArray().forEach(function(value, index) {
    s += index+" = "+value+"\n";
});

Or reduce:

var s = GetArray().reduce(function(previousValue, currentValue, index) {
    return (index == 1 ? getLine(0, previousValue) : previousValue) + getLine(index, currentValue);
});
function getLine(index, value) {
    return index +" = "+value+"\n";
}
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
2
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

Community
  • 1
  • 1
Graeme Wicksted
  • 1,770
  • 1
  • 18
  • 21
2

Answer is YES, if you do not use any library such as jQuery or Underscore, you can use forEach:

GetArray().forEach(function(value, key) {
    // blabla
});

You can find other replacement in Underscore library like:

_.each(GetArray(), function(value, key) {
    // blabla
});
wizcabbit
  • 36
  • 3