Problem mit "undefiniert"
Julia
- javascript
text = "000120"
function Los(text) {
var t1 = text.charAt(0) + text.charAt(1) ;
var t2 = text.charAt(2) + text.charAt(3) ;
var t3 = text.charAt(4) + text.charAt(5) ;
alert(t1)
window.setTimeout("Count(t1, t2, t3)", 100);
}
Es soll also eine Funktion Count() mit t1, t2 und t3 gestartet werden.
Fehlermedung:
Zeile 1 Zeichen 1
't1' ist undefiniert
Das komische ist, dass alert 00 ausgibt.
Lösungsversuche:
if (typeof(t1)=="undefined"){t1="0"}
if (t1 == "00") {t1=0}
kann mir bitte jemand helfen?
Danke schon mal im vorraus.
Hallo,
text = "000120"
function Los(text) {
var t1 = text.charAt(0) + text.charAt(1) ;
var t2 = text.charAt(2) + text.charAt(3) ;
var t3 = text.charAt(4) + text.charAt(5) ;
alert(t1)
window.setTimeout("Count(t1, t2, t3)", 100);
}Es soll also eine Funktion Count() mit t1, t2 und t3 gestartet werden.
Durch das Schlüsselwort »var« beim Notieren der Variablen t1, t2 und t3 sagst du aus, dass sie nur im Kontext der momentanen Ausführung der Funktion Los() Gültigkeit haben. Der nach dem Timeout ausgeführte Code wird aber außerhalb dieses Kontexts ausgeführt.
Wenn du beispielsweise folgende schreibst:
function meinefunktion () {
var variable=123;
window.setTimeout("window.alert(variable)", 100);
}
meinefunktion();
Dann findet window.alert() variable nicht (undefined).
Wenn du hingegen das »var« weglässt, sollte es klappen:
function meinefunktion () {
variable=123;
window.setTimeout("window.alert(variable)", 100);
}
meinefunktion();
Dasselbe gilt entsprechend für selbst erstellte Funktionen:
function funktion_a () {
variable=123;
window.setTimeout("funktion_b(variable)", 100);
}
function funktion_b (zahl) {
window.alert(zahl);
}
funktion_a();
Es gibt natürlich noch komplizierte Möglichkeiten, die erlauben, weiterhin »var« zu verwenden, sofern nötig.
Mathias
Hi Mathias,
vielen dnak für deinen tipp, dass Programm läuft.
Julia