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.

1 Answer 1

1

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.

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

2 Comments

That's it. When you do var secret = new Array(setSecretCode(...)) you wind up with an array that contains the result of the function, which is also an array, i.e. [[1,5,3,2,3,4]]. So, secret[0] = [1,5,3,2,3,4]
Ha! so simple a fix. Thank you very much.

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.