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