2

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)

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

To be more precise : the undefined that you see is the value of your test variable. The others displayed log are those of console.log(array).
0

You are not returning any value from the function, that's why it is showing undefined. Variable "test" does not have any data.

Try this:

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);
 return array;
}
var test = arrayMaker(10)
console.log(test)

Comments

Your Answer

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.