musikluver2003
musikluver2003

Reputation: 163

What am I doing wrong with this array?

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

Upvotes: -1

Views: 62

Answers (2)

Shomz
Shomz

Reputation: 37701

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.

Upvotes: 6

Jason
Jason

Reputation: 13766

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.

Upvotes: 2

Related Questions