Nul*_*teя 115 javascript
我正在使用JavaScript,我创建了一个全局变量.我在函数之外定义它,我想从函数内部更改全局变量值并从另一个函数使用它,我该怎么做?
Spu*_*ley 138
只需引用函数内部的变量; 没有魔法,只要用它的名字.如果它是全局创建的,那么您将更新全局变量.
您可以通过在本地使用声明它来覆盖此行为var
,但如果您不使用var
,那么如果已全局声明该变量,则函数中使用的变量名称将是全局的.
这就是为什么始终明确声明变量的最佳实践var
.因为如果你忘了它,你可以意外地开始搞乱全局变量.这是一个容易犯的错误.但在你的情况下,这种转变并成为你问题的简单答案.
Chr*_*ris 56
var a = 10;
myFunction();
function myFunction(){
a = 20;
}
alert("Value of 'a' outside the function " + a); //outputs 20
Run Code Online (Sandbox Code Playgroud)
yun*_*zen 26
只需使用该变量的名称即可.
在JavaScript中,变量只是函数的本地变量,如果它们是函数的参数,或者通过var
在变量名称前键入关键字来明确地将它们声明为本地变量.
如果本地值的名称与全局值具有相同的名称,请使用该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 5:', window.z, z) // global z, same as z, because z is not local
}
a(10);
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 5:', z); // global z, overwritten in function a
Run Code Online (Sandbox Code Playgroud)
与ES2015那两个更多的关键字const
和let
,这也影响的变量的范围(语言规范)
var a = 10;
myFunction(a);
function myFunction(a){
window['a'] = 20; // or window.a
}
alert("Value of 'a' outside the function " + a); //outputs 20
Run Code Online (Sandbox Code Playgroud)
使用 window['variableName']或window.variableName您可以修改函数内全局变量的值。
<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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
311829 次 |
最近记录: |