所以我需要一个增加变量值的函数,比如说n = 0。当函数运行时,此变量的值必须递增,并且不应再次等于0。例如,考虑以下代码:
So I need a function which increments the value of a variable say n=0. When ever the function runs, the value of this varible must be incremented and it should not be equal to 0 again. For example consider the following code :
function increment(){ var n = 0; n++; return n; }现在每次运行此函数时,您得到的值为1.但是我的要求如果你第一次运行这个函数,它应该是1,如果你第二次运行它,它应该是2,依此类推。除非您刷新html页面并再次运行该函数,否则它不应该等于0.任何人都可以帮助我吗?
Now everytime you run this function you get a value of 1. But my requirement is if you run this function for the 1st time, it should be 1, if you run it for the second time, it should be 2 and so on. Unless you refresh the html page and run the function again, it should not be equal to 0. Can anybody help me?
我是新手编码和任何小帮助非常感谢。在此先感谢!!!
I'm new to coding and any small help is appreciated. Thanks in advance!!!
推荐答案您需要在函数外部声明n。
You need to declare n outside of the function.
var n = 0; function increment(){ n++; return n; }问题在于范围。当您在函数内部声明变量时,它将绑定到函数的本地范围。一旦函数完成,变量就会消失。
The problem is scopes. when you declare a variable inside of a function it is bound to the local scope of the function. as soon as the function is done the variable is gone.
声明脚本根级别的变量将其置于全局范围内。
declaring the variable in the root level of the script places it in the global scope.
另一种方法是在外面传递一个变量,然后通过参数将其传递给函数。
another way to do this would be to have a variable outside that you're passing around and then you pass it to the function via a parameter.
var i = 0; function increment(n){ n++; return n; } i=increment(i);有关范围和变量的更多信息,请查看此页面:developer.mozilla/en-US/docs/Web/JavaScript/Guide/Values ,_variables,_and_literals#Variable_scope
for more information on scopes and variables, review this page: developer.mozilla/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Variable_scope
更多推荐
每次运行功能时增加值
发布评论