+ 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
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
+ 2
ForLoop its defined but the name its visible only inside itself
+ 2
Calviղ Didn't know you could make variables functions. Thanks.
+ 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.