每次运行功能时增加值

时间:2014-02-17 21:47:22

标签: javascript

所以我需要一个增加变量值的函数,比如说n = 0。当函数运行时,此变量的值必须递增,并且不应再次等于0。例如,请考虑以下代码:

function increment(){
  var n = 0;
  n++;
  return n;
}

现在每次运行此函数时,您得到的值为1.但我的要求是,如果您第一次运行此函数,它应该是1,如果您第二次运行它,它应该是2,所以上。除非你刷新html页面并再次运行该函数,否则它不应该等于0.任何人都可以帮助我吗?

我是编码的新手,感谢任何小帮助。在此先感谢!!!

7 个答案:

答案 0 :(得分:27)

创建closure以保存值

  

闭包是指独立(自由)变量的函数。

     

简而言之,闭包的父函数中的变量仍然与父级的范围绑定。

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

答案 1 :(得分:12)

你需要在函数之外声明n。

var n = 0;

function increment(){

  n++;
  return n;
}

问题在于范围。当您在函数内部声明变量时,它将绑定到函数的本地范围。一旦功能完成,变量就会消失。

声明脚本根级别的变量将其置于全局范围内。

另一种方法是在外面传递一个变量,然后通过参数将它传递给函数。

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

答案 2 :(得分:3)

您可以将数据绑定到函数(因为函数是对象)。

function increment(){
    increment.n = increment.n || 0;
    return ++increment.n;
}

答案 3 :(得分:0)

var n = 0;
function increment(){
  n++;
  return n;
}

答案 4 :(得分:0)

了解范围将对您有所帮助。你想要的是变量'n'是全局范围的。

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

答案 5 :(得分:0)

如何使次数增加称为参数?

function increment(numberOfIncrementCalls){
numberOfIncrementCalls++;
return numberOfIncrementCalls;
}

function increment(numberOfIncrementCalls){
    numberOfIncrementCalls++;
    return numberOfIncrementCalls;
    }
n = document.getElementById("demo");
o = document.getElementById("event");
numOfIncr = 0;
o.addEventListener("click",function(){
numOfIncr = increment(numOfIncr);
var insert = numOfIncr.toString();
n.innerHTML = insert;
});
<html>
<p id="demo"></p>
<button id="event">Click me</button>
</html>

答案 6 :(得分:0)

您可以尝试使用此代码并将值存储在 localstorage 中。它会一直增加旧值,直到您没有清除本地存储...

<script>
    localStorage.setItem("n", 0);
    increment();
    function increment(){
    let n;
    n = localStorage.getItem('n');
    n++;
    localStorage.setItem("n", n);
    return n;
    }
</script>
相关问题