Javascript 变量以保持总数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5185844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:02:16  来源:igfitidea点击:

variable to keep total count

javascriptjquerycookies

提问by santa

I'm using jQuery and run various functions that add numeric values to the same counter. I need to be able to keep that counter number growing as I add values, in order for my functions to access the current total and add new sums to it. How do I do that? Do I store it in a cookie and retrieve from the cookie before adding more? A bit lost here...

我正在使用 jQuery 并运行各种将数值添加到同一个计数器的函数。我需要能够在添加值时保持该计数器编号的增长,以便我的函数访问当前总数并向其添加新的总和。我怎么做?我是否将其存储在 cookie 中并在添加更多之前从 cookie 中检索?有点迷失在这里...

回答by Orbit

I'm not sure if this is wrong, but I often keep it in a global variable.

我不确定这是否是错误的,但我经常将它保存在一个全局变量中。

<script>

    var count= 0;

    function incrementCount(){
       count++;
    }

    console.log(count);
    incrementCount();
    console.log(count);   

</script>

回答by user460847

Using a global variable works, but if you have other global variables, it's worth it to make one global variable and have all the others be properties of that variable. (Globals can interfere with third-party scripts on your page.) So for your counter, make the global variable: var MYAPP = {}; and then the counter property MYAPP.counter = 0;. Then increment MYAPP.counterwhen appropriate.

使用全局变量是可行的,但是如果您有其他全局变量,那么创建一个全局变量并使所有其他变量成为该变量的属性是值得的。(全局变量可能会干扰您页面上的第三方脚本。)因此,对于您的计数器,创建全局变量:var MYAPP = {}; 然后是 counter 属性MYAPP.counter = 0;。然后MYAPP.counter在适当的时候增加。

回答by Richard Pianka

Just use a global variable in your Javascript.

只需在您的 Javascript 中使用全局变量。