Micha Micha - 3 months ago 13
Javascript Question

javascript function array variable an function schicken

ich brauche dringend Eure Hilfe, zur Verständnis.
Im 1. Beispiel funktioniert mein Test Script normal.
im 2. habe ich die beiden Abschnitte in jeweils eine Funktion gepackt und in der Console folgender Fehler angezeigt:


Uncaught ReferenceError: test is not defined : test_js.html:26


Frage, wie kann ich denn die Arrays in der 2. Funktion auslesen?



<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<script language="javascript">

var test = new Array();

for(a=0; a<19;a++) {

test[a]= " bla bla "+a;
}

</script>
<body>


<div>
<script language="javascript">


for(b=0; b<test.length;b++){
document.write('<a href="'+test[b]+'">'+test[b]+'</a><br><hr>');
}

</script>
</div>
</body>
</html>







<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<script language="javascript">
function a(){
var test = new Array();

for(a=0; a<19;a++) {

test[a]= " bla bla "+a;
}
}

a();
</script>
<body>


<div>
<script language="javascript">
function zeig(){

for(b=0; b<test.length;b++){
document.write('<a href="'+test[b]+'">'+test[b]+'</a><br><hr>');
}}
zeig();

</script>
</div>
</body>
</html>




Answer

When you use var to create a variable inside the scope of a function, that variable goes away when you exit the function. In your second example, you create the variable test from within the scope of a(). test is no longer available when you exit a(). MSDN has a page illustrating this.

To rearrange your code such that scopes remain largely the same, you might do something like:

function a(){
    var test = new Array();
    for(var a=0; a<19; a++) {
        test[a] = " bla bla "+a;
    }
    return test;
}
function b(something) {
    for(var b=0; b<something.length; b++){
        document.write('<a href="'+something[b]+'">'+something[b]+'</a><br><hr>');
    }
}
b(a());