gpt4 book ai didi

javascript - 了解本地范围

转载 作者:行者123 更新时间:2023-11-30 13:26:02 25 4
gpt4 key购买 nike

无论我多么努力,我都无法改变“i”的值...

我的代码如下:

function changeValue(){
//neither 'var i=99;' or 'i=99;' interferes with the 'i' on myFunction
}

function myFunction(){
var i;

for(i=0;i<3;i++){
alert(i);
changeValue();
alert(i);
}
}

myFunction();

我的问题:如何使用 changeValue 函数更改“i”的值(在 MyFunction 上)?

另外:我非常需要阅读一些关于这方面的指南,有人可以给我一个好的链接吗?

最佳答案

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

关于javascript - 了解本地范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8436358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com