Jump to content

Adding Values To An Array.


jimmac

Recommended Posts

Hi all, I am very new to javascript, 2 weeks now, and have just started using array's. I have already looked through the website, but could not find anything relating to my problem. I have an array which already has 5 elements/values and want to add the data of window prompts, equal to the array length, to the original values of my array. for example, if i have an array:- array[1,2,3,4,5] , and the first window prompt input was '1' , the first element of the array would then change to 2The code I have so far is:-var a, b;var c = [230,341,196,81,257];a = parseFloat (window.prompt('How many members are there in total?', ''));for (var d = 0; d <c.length; d = d + 1){ c[d] = parseFloat (window.prompt('Please enter the votes cast for candidate ' + (d + 1),'')); }Forgive me if there are in fact examples already somewhere in the tutorials or forum.Can anyone help or point me in the right direction.Thanks for any help.jimmac

Link to comment
Share on other sites

Thanks for the quick reply.I want to display the information and used, document.write(); to try and display and confirm that my code works. I assumed my code doesn't work. After each window prompt, i only know how to display each value as a string or the sum of each window prompt.How would I use document.write(); to display the original values of the array with each value of the window prompts added to them?

Link to comment
Share on other sites

First, don't use document.write(). Didn't you look at my signature? :)You can use a for loop to access the values of your array. Use a new one, or just do it in the loop you have. Add a div to your HTML section, like this:<div id="msg"> </div>Then, in your loop, AFTER you assign the value to the array element, add a statement like this:document.getElementById('msg').innerHTML += c[d] + "<br>";The array values should print on separate lines

Link to comment
Share on other sites

Script statements are interpreted in two ways: as the page loads, or after page-load. When document.write() is called as the page loads (when it appears in a script, but outside a function), document.write() has some use. Other techniques are perhaps more useful.But when it appears in a function that is called AFTER page-load, it completely destroys the existing page and replaces it with whatever it writes.This behavior confuses the heck out of a lot of newbies.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...