每次运行功能时增加值 [英] Increment value each time when you run function

查看:79
本文介绍了每次运行功能时增加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我需要一个增加变量值的函数,比如说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);

有关范围和变量的更多信息,请查看此页面:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values ,_variables,_and_literals#Variable_scope

for more information on scopes and variables, review this page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Variable_scope

这篇关于每次运行功能时增加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆