我是javascript的新手,并且在计数程序方面遇到了麻烦,我认为在可变范围方面可能会遇到麻烦。
var count = 0; {
function gimmeRandom() {
var rand = Math.floor(Math.random() * 10) + 1;
count++;
}
function countToRandom() {
for (count = 1; count <= rand; count++) {
console.log(count);
}
}
console.log("Counting to a random number");
gimmeRandom();
countToRandom();
console.log("Counting to another random number");
gimmeRandom();
countToRandom();
console.log("There has been " + count + " random numbers used");
}
答案 0 :(得分:1)
您在var rand
内声明了gimmeRandom
,无法在countToRandom
中访问它。您可能想要一个全局变量,就像使用count
一样。
答案 1 :(得分:0)
在函数内部声明var会使该变量作用于函数。您有两种选择。
var count = 0;
{
function gimmeRandom()
{
rand = Math.floor(Math.random()*10)+1;
count++;
}
function countToRandom()
{
for (count = 1; count <= rand; count++)
{
console.log(count);
}
}
console.log("Counting to a random number");
gimmeRandom();
countToRandom();
console.log("Counting to another random number");
gimmeRandom();
countToRandom();
console.log("There has been "+count+" random numbers used");
}
var count = 0;
var rand = 0;
{
function gimmeRandom()
{
rand = Math.floor(Math.random()*10)+1;
count++;
}
function countToRandom()
{
for (count = 1; count <= rand; count++)
{
console.log(count);
}
}
console.log("Counting to a random number");
gimmeRandom();
countToRandom();
console.log("Counting to another random number");
gimmeRandom();
countToRandom();
console.log("There has been "+count+" random numbers used");
}
答案 2 :(得分:0)
您定义要在此函数中受限制的兰特:
4.1.9
然后尝试在其他功能中使用它:
function gimmeRandom() {
var rand = Math.floor(Math.random() * 10) + 1;
count++;
}
如该问题所示:
What is the scope of variables in JavaScript?
您定义的变量 function countToRandom() {
for (count = 1; count <= rand; count++) {
console.log(count);
}
}
被赋予gimmeRandom()函数一个本地范围,因此不能在该函数之外使用。
要在函数中使用它,您可能希望使变量具有全局作用域