选择数组中的随机索引&从不同的函数调用变量。 JavaScript的

时间:2016-06-13 21:53:39

标签: javascript arrays algorithm function variables

我无法访问通过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);
        }
}

1 个答案:

答案 0 :(得分:1)

几个问题:

  • randomTest永远不会得到它的值,因为您在到达该代码之前退出了该函数。但即使您在其后移动return语句,也无法从函数体外部访问它。
  • 您永远不会执行函数createTest_Var。代码createTest_Var.randomTest尝试访问函数对象的未存在属性。要调用该函数,您应该编写createTest_Var()
  • 即使您要调用它,由于第一个问题,您实际上仍然没有从生成的数组中选择随机元素。为此,您可以编写一个单独的函数,并将其命名为:pickFromArray(createTest_Var())
  • testNumber[i].length不正确:你想要数组的长度,而不是第i个元素,所以写testNumber.length

以下是更正的代码:

&#13;
&#13;
//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;
&#13;
&#13;