简体   繁体   English

从函数更新全局值

[英]Updating Global Value from a Function

everybody. 每一个人。 I'm working on a project and I have two functions for a slideshow using the same global variable. 我正在做一个项目,并且我有两个使用相同全局变量的幻灯片放映功能。 I want the value to carry between the functions, instead of resetting to 1 every time you switch. 我希望该值在函数之间传递,而不是每次切换时都重置为1。 Is it possible to permanently update a global variable from a function or do I need to really rethink my code? 是否可以从函数中永久更新全局变量,或者我是否需要重新思考代码?

You basically answered your own question, as long as the variable is global and let or var . 只要变量是global和letvar ,就可以基本上回答自己的问题。 You can't permanently change something in JS. 您不能永久更改JS中的某些内容。 With that being said, let variables can't become const and const variables can become let but you can keep a value inside a function or make it global and change the value of it through a function. 话虽如此,let变量不能成为const,而const变量可以成为let,但是您可以将值保留在函数内或将其设为全局值并通过函数更改其值。 Try something like this: 尝试这样的事情:

let myVariable = 0;

const loopOne = () => {

    for(let i = 0; i < 5; i++){

        myVariable++;
    };
  return true;
};

const loopTwo = () => {

    for(let i = 0; i < 5; i++){

        myVariable++;
    };
  return true;
};

loopOne();
loopTwo();


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM