Matthew Morris Matthew Morris - 7 months ago 9
Javascript Question

Why would there be a undefined at the end of this array?

I'm trying to make a simple array with random text. I always see undefined after the end of the array though. Is there any way to remove it? I've searched and tried [i-1], but no luck.

function arrayMaker(integer) {
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var array = [];
for (q = 0; q < integer; q++){
var word = '';
for (i = 0; i < Math.floor((Math.random() * 10) +1); i++){
var number = Math.floor(Math.random() * 26);
word += alphabet.substring(number, (number+1));
}
array.push(word);
}
console.log(array);
}
var test = arrayMaker(10)
console.log(test)

Answer

You do not return something. Add

return array;

Then you get the array, you want.

If you use just return or no return, then undefined is returned.

function arrayMaker(integer) {
    var alphabet = "abcdefghijklmnopqrstuvwxyz",
        array = [], q, i, number, word;
    for (q = 0; q < integer; q++) {
        word = '';
        for (i = 0; i < Math.floor((Math.random() * 10) + 1) ; i++) {
            number = Math.floor(Math.random() * 26);
            word += alphabet.substring(number, (number + 1));
        }
        array.push(word);
    }
    return array;
}
var test = arrayMaker(10);

document.write('<pre>' + JSON.stringify(test, 0, 4) + '</pre>');

Comments