Javascript Snippets

Globale Variablen in Javascript

Typing var before the variable in a function makes it local in the function.
Without var in a function makes it global.
Typing var outside a function makes it global.

function foo () {
var bar = []; /* This is scoped to the function */
bar = []; /* This is a global. */
}

var bar = []; /* This is a global */

 

Zufallszahlen aus einem Array

function randomZahl(min, max){
return Math.floor(Math.random() * (max – min + 1)) + min;
}

myArray = new Array(49);
var myZahl = 0;
for (var i = 0; i < myArray.length; ++i){
myZahl = i+1;
myArray[i] = myZahl;
}
var myRandomValue = randomZahl(0, 48);
var myValue = myArray[myRandomValue]; /*Zufallszahl aus Array*/

Schreibe einen Kommentar