移動changeValue()
是在相同的範圍內i
:
function myFunction(){
var i;
for(i=0;i<3;i++){
alert(i);
changeValue();
alert(i);
}
function changeValue() { i = 99; }
}
或者,把i
在相同的範圍內爲changeValue()
:
var i;
function changeValue() { i = 99; }
function myFunction(){
// var i; // don't define i here
for(i=0;i<3;i++){
alert(i);
changeValue();
alert(i);
}
}
或者,你可以告訴changeValue()
什麼價值i
是,然後讓它返回新值:
function changeValue(i) {
return i + 1;
}
然後:
i = changeValue(i);
編輯:爲了說明範圍:
var a = 0; // global scope - accessible everywhere via a
// unless overridden by a locally scoped a
// always accessible via window.a
function doSomething() {
var a = 1; // local scope - you can still access window.a
var b = 2; // local scope - accessible to child scopes, but not global scope
function innerFunction() {
var a = 3; // you no longer have access to the parent function's a variable
// you can still access window.a
var c = 4; // only accessible here (since no child scopes exist)
alert(window.a); // 0
alert(a); // 3
alert(b); // 2
alert(c); // 4
}
innerFunction();
alert(window.a); // 0
alert(a); // 1
alert(b); // 2
alert(c); // undefined - unavailable in this scope
}
doSomething();
alert(window.a); // 0
alert(a); // 0
alert(b); // undefined - unavailable in this scope
alert(c); // undefined - unavailable in this scope
*「瞭解本地範圍」*本地範圍是通過函數聲明定義的。當你使用'var'語句聲明變量的函數中時,變量在本地作用域中定義。該函數之外的任何內容都不會訪問該變量。 – RightSaidFred
人們似乎喜歡[Eloquent JavaScript](http://eloquentjavascript.net/)。 [Chapter 2](http://eloquentjavascript.net/chapter2.html)具有變量的基礎知識,然後[Chapter 3](http://eloquentjavascript.net/chapter3.html)進入函數的變量範圍。 – RightSaidFred