2 回答

TA贡献1803条经验 获得超6个赞
您编写了代码,但从未调用过它。fun1并且fun2永远不会运行。我在下面添加了一行,它调用了fun1()导致分配发生的函数。
这更像是提供演示的答案——您很可能不想实际编写具有全局变量或像这样的副作用的代码。如果您正在为浏览器编写软件,使用window或globalThis存储您的全局状态也可能使它更清晰。
// Declare the myGlobal variable below this line
var myGlobal = 10
function fun1() {
// Assign 5 to oopsGlobal Here
oopsGlobal = 5
}
fun1(); // You wrote the functions previous, but you never CALLED them.
// Only change code above this line
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
console.log(oopsGlobal) // ReferenceError: oopsGlobal is not defined

TA贡献1895条经验 获得超7个赞
发生这种情况是因为您实际上从未跑步过fun1()。如果你不调用一个函数,里面的代码将永远不会被执行。
参考错误:
// Declare the myGlobal variable below this line
var myGlobal = 10
function fun1() {
// Assign 5 to oopsGlobal Here
oopsGlobal = 5
}
// Only change code above this line
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
console.log(oopsGlobal) // ReferenceError: oopsGlobal is not defined
没有 ReferenceError(注意是之前fun1()调用的) console.log()
// Declare the myGlobal variable below this line
var myGlobal = 10
function fun1() {
// Assign 5 to oopsGlobal Here
oopsGlobal = 5
}
// Only change code above this line
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
fun1()
console.log(oopsGlobal)
添加回答
举报