Stiggandr Stiggandr - 2 years ago 66
Javascript Question

Modify multiple array elements simultaneously javascript

I'm making a simple rogue like game in JavaScript. I can generate a map procedurally without any issue, however I'm looking for a more ergonomic way of manually populating a map array. Here's an example of what I'm talking about.

This works.

//creating empty map array
city = new Array(1500);

//creating tile formats
tile1 = {walk: true, ...etc};
tile2 = {walk: false, ...etc};

//manually modifying array.
city[0] = tile1;
city[1] = tile1;
city[2] = tile1;

However, since some of these maps will be rather large, I'd like to be able to modify multiple elements all at once. The following doesn't work, but expresses what I'd like to do.

city[0,1,2,3,7,8,9,10] = tile1;
city[4,5,6,11,12,13] = tile2;

I tried quite a few different methods, but wasn't successful with any of them. I can't use a for statement without using math more complicated than it'd be worth since I'm using a single array to represent 2d space, and the tiles are not sequential.

Any suggestions?

Answer Source

Use forEach with ES6 arrow function in latest browsers

//creating empty map array
city = new Array(1500);

//creating tile formats
tile1 = {
  walk: true
tile2 = {
  walk: false

[0, 1, 2, 3, 7, 8, 9, 10].forEach(v => city[v] = tile1);
// older browser use [0, 1, 2, 3, 7, 8, 9, 10].forEach(function(v){ city[v] = tile1; });
[4, 5, 6, 11, 12, 13].forEach(v => city[v] = tile2);


For older browser check polfill option of forEach method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download