我无法访问通过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);
}
}
几个问题:
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句