1

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?

1
  • You can not really do it that way! To assign a value to key, you need to specify specific key.. To do it for many indexes/keys, use a loop..There is no valid address as city[0,1,2,3,7,8,9,10] Commented May 21, 2016 at 5:12

1 Answer 1

1

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);

console.log(city);

For older browser check polfill option of forEach method.

Sign up to request clarification or add additional context in comments.

4 Comments

Why not just fill?
@Roque 4, 5, 6, 11, 12, 13 , you cant just use the range here 7,8,9,10 are missing
This suites the exact purpose that I'm looking for. Tested, and successful. Thank you. fill would not suite my needs because I'm working with dozens of different tiles in very particular placements. I would have to use multiple fill statements to achieve the same effect as one forEach statement.
isn't there a way to do this without looping?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.