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)
添加回答
舉報