+ 2

Why is my onload function undefined?

Ok, so I decided to play around with for loops. I was bored and curious. I came across this strange error (click the button). ForLoop is clearly defined...Right? https://code.sololearn.com/Wm9wjWaFtrlZ/?ref=app

22nd Sep 2018, 6:36 AM
Daniel Cooper
Daniel Cooper - avatar
4 Antworten
+ 6
Try this var forLoop = function() { var i; var arr = []; for(i=0; i<=10; i++) { arr.push(i); alert(arr); } document.getElementById("MyButton").addEventListener("click", reset); }; function reset() { i = 0; forLoop(); } window.onload = forLoop; https://code.sololearn.com/WATNj2tj3E3j/?ref=app
22nd Sep 2018, 7:04 AM
Calviղ
Calviղ - avatar
+ 2
ForLoop its defined but the name its visible only inside itself
22nd Sep 2018, 6:43 AM
KrOW
KrOW - avatar
+ 2
Calviղ Didn't know you could make variables functions. Thanks.
22nd Sep 2018, 7:15 AM
Daniel Cooper
Daniel Cooper - avatar
+ 1
ForLoop is visible inside function declaration (see js scope doc). But in your case you can call window.onload as it is the same and is visible globally. function Reset() { i = 0; window.onload(); } It looks not perfect at all, but works. Writing a separate function is a better idea in order to understand the code.
22nd Sep 2018, 9:17 AM
Микола Федосєєв
Микола Федосєєв - avatar