Increment value each time when you run function

2020-02-09 08:30发布

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;
}

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!!!

标签: javascript
5条回答
我命由我不由天
2楼-- · 2020-02-09 08:50

You can bind the data to the function (since functions are objects).

function increment(){
    increment.n = increment.n || 0;
    return ++increment.n;
}
查看更多
三岁会撩人
3楼-- · 2020-02-09 08:50

Learning about scopes will help you greatly. What you want here is the variable 'n' to be of a global scope.

 var n = 0; //Declare n outside of the function makes it accessible to the function
            //and to any other functions or expressions that want access to n
 function inc() {
     n++;
 }
查看更多
够拽才男人
4楼-- · 2020-02-09 09:09
var n = 0;
function increment(){
  n++;
  return n;
}
查看更多
何必那么认真
5楼-- · 2020-02-09 09:11

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);

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

查看更多
爷、活的狠高调
6楼-- · 2020-02-09 09:17

Create a closure to hold the value

Closures are functions that refer to independent (free) variables.

In short, variables from the parent function of the closure remain bound from the parent's scope.

var increment = (function(n) {
  return function() {
    n += 1;
    return n;
  }
}(0)); // -1 if you want the first increment to return 0

console.log(increment());
console.log(increment());
console.log(increment());

查看更多
登录 后发表回答