我是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");
}
你在var rand
中声明了gimmeRandom
,你无法在countToRandom
中访问它。您可能想要一个全局变量,就像使用count
一样。
将函数范围内的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");
}
您可以在此函数中定义rand:
function gimmeRandom() {
var rand = Math.floor(Math.random() * 10) + 1;
count++;
}
然后尝试在另一个函数中使用它:
function countToRandom() {
for (count = 1; count <= rand; count++) {
console.log(count);
}
}
如这个问题所示:
What is the scope of variables in JavaScript?
您定义的变量rand
被赋予gimmeRandom()函数的局部范围,因此不能在该函数之外使用。
要在函数中使用它,您可能希望使变量具有全局范围