我无法访问通过randomTest选择的随机索引。当我在analytics_test()中调用randomTest时,我收到一个未定义的错误。我觉得好像我实际上并没有访问这个变量。任何提示或想法来解决这个问题?我很感激,谢谢!
//This function creates a loop for 5 random numbers. Each index in the array is given a variable
function createTest_Var() {
var testNumber = [];
var i;
for (i = 0; i < 5; i++) {
testNumber[i] = (Math.random() * 10);
}
var randomTest = testNumber[Math.floor(Math.random() * testNumber[i].length)];
return testNumber;
}
//This function takes chooses a random index from the array and compares it to the random number "y".
function analytics_test() {
var y = (Math.random() * 10);
var i = createTest_Var.randomTest;
if (y < i) {
//Just a test console.log ("the random numbers are: " + (Math.random() * 10));
console.log ("It is greater! " + i + "<" + y);
}
else {
console.log("not big enough " + i + ">" + y);
}
}
答案 0 :(得分:1)
几个问题:
randomTest
永远不会得到它的值,因为您在到达该代码之前退出了该函数。但即使您在其后移动return
语句,也无法从函数体外部访问它。createTest_Var
。代码createTest_Var.randomTest
尝试访问函数对象的未存在属性。要调用该函数,您应该编写createTest_Var()
pickFromArray(createTest_Var())
testNumber[i].length
不正确:你想要数组的长度,而不是第i个元素,所以写testNumber.length
。以下是更正的代码:
//This function creates a loop for 5 random numbers. Each element in the array is given a value
function createTest_Var() {
var testNumber = [];
var i;
for (i = 0; i < 5; i++) {
testNumber[i] = (Math.random() * 10);
}
return testNumber;
}
// Function to pick random element from array
function pickFromArray(testNumber) {
return testNumber[Math.floor(Math.random() * testNumber.length)];
}
//This function takes chooses a random element from the array and compares it to the random number "y".
function analytics_test() {
var y = (Math.random() * 10);
var i = pickFromArray(createTest_Var());
if (y < i) {
//Just a test console.log ("the random numbers are: " + (Math.random() * 10));
console.log ("It is greater! " + i + "<" + y);
}
else {
console.log("not big enough " + i + ">" + y);
}
}
analytics_test();
&#13;