2 回答

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超6個(gè)贊
您編寫(xiě)了代碼,但從未調(diào)用過(guò)它。fun1并且fun2永遠(yuǎn)不會(huì)運(yùn)行。我在下面添加了一行,它調(diào)用了fun1()導(dǎo)致分配發(fā)生的函數(shù)。
這更像是提供演示的答案——您很可能不想實(shí)際編寫(xiě)具有全局變量或像這樣的副作用的代碼。如果您正在為瀏覽器編寫(xiě)軟件,使用window或globalThis存儲(chǔ)您的全局狀態(tài)也可能使它更清晰。
// 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貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
發(fā)生這種情況是因?yàn)槟鷮?shí)際上從未跑步過(guò)fun1()。如果你不調(diào)用一個(gè)函數(shù),里面的代碼將永遠(yuǎn)不會(huì)被執(zhí)行。
參考錯(cuò)誤:
// 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
沒(méi)有 ReferenceError(注意是之前fun1()調(diào)用的) 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)
添加回答
舉報(bào)