0
我對JS(以及其他所有東西)都很陌生,我試圖用一個函數來生成一個隨機數組,然後將該數組傳回給主要的。我似乎正在按照我的意願創建數組數組,但是隨後整個數組被放入第一個位置(數組[0]),並且數組的長度爲一個位置。 我試圖在別處找到這個問題,但沒有看到任何與我的問題相匹配的東西。Javascript函數返回位置[0]整個數組
下面的代碼:
//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!
感謝您的任何反饋。
就是這樣。當你執行'var secret = new Array(setSecretCode(...))'時,你得到一個包含函數結果的數組,也就是一個數組,也就是'[[1,5,3,2, 3,4]]'。所以,'secret [0] = [1,5,3,2,3,4]' – jackwanders
哈!這麼簡單的修復。非常感謝你。 – johntreml