1

I have an array of divs, currently 10x10 in html. I also have a 100 big array in Javascript. They look like this.

<div class = "mapArrayA" id = "a1">1</div>
<div class = "mapArrayA" id = "a2">2</div>
<div class = "mapArrayA" id = "a3">3</div>
<div class = "mapArrayA" id = "a4">4</div>
<div class = "mapArrayA" id = "a5">5</div>

//

var mapArray = [];
mapArray[1] = 0; 
mapArray[2] = 0;
mapArray[3] = 0;
mapArray[4] = 0;
mapArray[5] = 0;

The Javascript array will be filled with randomly generated numbers 1-5, with no duplicates using a simple loop. I then want the Javascript array to be visually placed on the divs (as text and eventually CSS modifications) as they follow; a1 should show the value in mapArray[1], and a4 on mapArray[4].

I couldn't find a solution other than I probably have to do something with $(this).text from jquery. Any help would be greatly appreciated.

1 Answer 1

1

Why don't you just do something like this:

$.each(mapArray, function(key, val){
    $("#a"+key).text(val);
});

If I'm understanding your question correctly.

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

3 Comments

This works exactly how I want it to work. I however do not understand exactly why it is working the way it does. What are key, and val, and why don't they need to be assigned as variables? I assume val is the value in the map array ie. 1-5, and the key is the corresponding number from the array to the div, however I still don't understand. Could you explain this to me please? If you can't, I thank you for helping me solve this!
Good, glad it does what you need. So .each takes a collection of objects, in your case an array mapArray, and then does something with each element function(key, val) which in the case of arrays gives the index and value of each element. Then you can do something using those values and just access each div by name set what text is in it. You could do something similar by giving all your divs the same class and then iterating through them with a counter to know what array index to set the value from.
Thanks again! That explains a lot. I just found it odd that key and val weren't variables. I haven't learned too much about jquery yet so this was very insightful and useful.

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.