如何更改函数内部全局变量的值

我正在使用 JavaScript 并创建一个全局变量。我在函数之外定义了它,我想改变函数内部的全局变量值,然后从另一个函数中使用它,我该怎么做呢?

532191 次浏览
var a = 10;


myFunction();


function myFunction(){
a = 20;
}


alert("Value of 'a' outside the function " + a); //outputs 20

只要使用该变量的名称。

在 JavaScript 中,如果变量是函数的参数,或者通过在变量名前键入 var关键字将它们显式声明为 local,那么它们只对函数是局部的。

如果本地值的名称与全局值的名称相同,则使用 window对象

看这个 Jsfiddle

x = 1;
y = 2;
z = 3;


function a(y) {
// y is local to the function, because it is a function parameter
console.log('local y: should be 10:', y); // local y through function parameter
y = 3; // will only overwrite local y, not 'global' y
console.log('local y: should be 3:', y); // local y
// global value could be accessed by referencing through window object
console.log('global y: should be 2:', window.y) // global y, different from local y ()


var x; // makes x a local variable
x = 4; // only overwrites local x
console.log('local x: should be 4:', x); // local x
  

z = 5; // overwrites global z, because there is no local z
console.log('local z: should be 5:', z); // local z, same as global
console.log('global z: should be 5:', window.z) // global z, same as z, because z is not local
}
console.log('global x: should be 1:', x); // global x
console.log('global y: should be 2:', y); // global y
console.log('global z: should be 3:', 3); // global z
a(10)
console.log('global x: should be 1:', x); // global x, unaltered
console.log('global y: should be 2:', y); // global y, unaltered
console.log('global z: should be 5:', z); // global z, overwritten in function a

剪辑

ES2015增加了两个关键字 constlet,它们也会影响变量(语言规格)的范围

只要引用函数内部的变量; 不要使用魔法,只要使用它的名称。如果它是全局创建的,那么您将更新全局变量。

可以通过使用 var在本地声明它来覆盖这种行为,但是如果不使用 var,那么如果在函数中使用的变量已经全局声明,那么该变量的名称将是全局的。

这就是为什么总是使用 var显式声明变量被认为是最佳实践的原因。因为如果你忘了它,你可以开始混乱的全局意外。这是个很容易犯的错误。但是在你的情况下,这种转变会成为你问题的简单答案。

<script>
var x = 2; //X is global and value is 2.


function myFunction()
{
x = 7; //x is local variable and value is 7.


}


myFunction();


alert(x); //x is gobal variable and the value is 7
</script>
var a = 10;


myFunction(a);


function myFunction(a){
window['a'] = 20; // or window.a
}


alert("Value of 'a' outside the function " + a); //outputs 20

使用 [‘ variableName’]VariableName,您可以修改函数中全局变量的值。

一个简单的方法是使用 Var

var apple = null;
const some_func =()=>{
apple = 25
}
some_func()
console.log(apple)