每次运行功能时增加值

编程入门 行业动态 更新时间:2024-10-24 22:22:59
本文介绍了每次运行功能时增加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

每次运行功能时增加值

本文发布于:2023-10-22 22:26:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1518912.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:增加值   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!