johntreml
johntreml

Reputation: 101

Javascript function returns entire array in position[0]

I'm very new to JS (and everything else too) and I'm trying to use a function to generate an array of random numbers in and then pass that array back to the main. I appear to be making the array of numbers as I wanted, but then the whole array gets put into position one (array[0]) and the array length reads as one position. I've tried to find this problem elsewhere, but don't see anything matching my problem.

Here's the code:

//sets up an array of numbers that will be the secret code
// code = quantity of digits, number = numerals used for each digit

setSecretCode = function(code,numbers){ 

    var secretCode = "0";
    var secret = [];

    console.log("using code = "+ code); //used to verify parameters are correct
    console.log("and numbers = "+numbers); 
for (i=0; i < code; i++){ 
        secret[i] = Math.floor(Math.random()*numbers+1);
        console.log("secret#"+ i+"is"+secret[i]);
    }
    return secret;   

};



//function call - passing user defined parameters
var secret = new Array (setSecretCode(enteredCode,enteredNumber));


//printout of array for debugging
console.log("secret code is: "+ secret);      // returns appropriate looking code
console.log("secret0 = "+ secret[0]);         // whole array appears in this position
console.log("secret1 = "+ secret[2]);         // shows up as undefined

console.log(secret.length); //this illuminates problem -  array is only one position!

Thank you for any feedback.

Upvotes: 0

Views: 410

Answers (1)

davidgoli
davidgoli

Reputation: 2495

That's because you have nested an array inside of an array: setSecretCode returns an array, and you're wrapping that array inside a new array when you do new Array (setSecretCode(enteredCode,enteredNumber));

In general, new Array() is almost never needed in Javascript. Just use the array literal [] - it's the same thing.

Upvotes: 1

Related Questions