-1

Okay, trying to put together a numeric array and arrange it in ascending order. The more I look, the more I confuse myself. The alerts come up as "undefined." What am I overlooking?

var random = new Array();
function main() {
 generate();
 original();
 ascending(random);
}
function generate() {
 document.write("Here are 25 Random Numbers:<br><br>");
 for (var i = 0; i < 25; i++) {
 random[i] = document.write(Math.floor(Math.random() * 100) + ", ");
 }
}
function original() {
 var storage = "";
 for (var i = 0; i < 25; i++) {
 storage += random[i] + ", ";
 }
 alert(storage);
}
function ascending(random) {
 var tempArray = random;
 var storage = "";
 random.sort(function (a, b) {
 return a - b
 });
 for (i = 0; i < 25; i++) {
 storage += tempArray[i] + ", ";
 }
 alert("ASCENDING- " + storage);
}
j08691
209k33 gold badges269 silver badges281 bronze badges
asked Nov 5, 2014 at 20:24
1
  • 2
    I see a variable and four functions. I don't see how you call any of them. Commented Nov 5, 2014 at 20:26

2 Answers 2

6

No need for document.write (not sure what were you trying to achieve with it), this is enough:

random[i] = Math.floor(Math.random() * 100);

Afterwards, if you need to convert it to a string for output, just join it:

random.join(",");

Here is your generate function:

var random = [];
function generate() {
 document.write("Here are 25 Random Numbers:<br><br>");
 for (var i = 0; i < 25; i++) {
 random[i] = Math.floor(Math.random() * 100);
 }
}
generate();
var str = random.join(', ');
document.write(str);


Note: try to avoid using document.write whenever you can.

answered Nov 5, 2014 at 20:26
Sign up to request clarification or add additional context in comments.

Comments

2

Take out your document.write() call in generate(), that prints a number out to your HTML document, just assign it directly to your array. You're assigning the result of that print out to your array, which is definitely not what you want.

answered Nov 5, 2014 at 20:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.