0

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
  • 190,436
  • 28
  • 232
  • 252
musikluver2003
  • 165
  • 1
  • 9

2 Answers2

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.

Community
  • 1
  • 1
Shomz
  • 36,161
  • 3
  • 52
  • 81
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.

Jason
  • 13,048
  • 2
  • 26
  • 40