-1

So there are a lot of questions about iterating over an array, but I found none that says how to get the transformed array back as the left side variable. I can always do a standard for loop with indicies but I was wondering if I could use something like a .foreach that would return a transformed array.

Psedo example: I have an array points which are made up of an object Phaser.Point

Such that I can write the following code

x = new Phaser.Polygon(points.foreach(function (point) {
      return new Phaser.Point(point.x+5, point.y+5)
});

new Phaser.Polygon takes an array of Phaser.Point objects

Mike
  • 5,918
  • 9
  • 57
  • 94
  • 4
    I think Array.prototype.map is your friend here – pethel Jul 23 '17 at 16:52
  • Thank you for those references... should I delete the post even though it now has one answer with 2 votes... I think this helped ` As of Chrome 58, seems the tables have turned. The for...of loop is now the fastest and hands down the best approach for semantics and performance. Array.map is still an order of magnitude slower, due to the overhead of the function call. ` – Mike Jul 23 '17 at 17:04

2 Answers2

2

In this case, you may want to use Array.prototype.map(). Here is an example from MDN:

var numbers = [1, 5, 10, 15];
var roots = numbers.map(function(x) {
   return x * 2;
});
// roots is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]

In your case:

x = new Phaser.Polygon(points.map(function (point) {
      return new Phaser.Point(point.x+5, point.y+5)
});

References:

ninjin
  • 1,118
  • 10
  • 12
1

You can use Array.map. Array.map returns new array.