Funktionen in Arrays

programmierer123

Aktives Mitglied
Hallo,
wie ist das gemeint, dass Arrays Funktionen speichern können?
// myArray[1] = myFunction;

// JavaScript variables can be objects. Arrays are special kinds of objects.
// Because of this, you can have variables of different types in the same Array.
// You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:
// myArray[0] = Date.now;
// myArray[1] = myFunction;
// myArray[2] = myCars;​
 

sascha-sphw

Top Contributor
Probiers doch mal aus.
Code:
var myArray = [];
myArray[0] = alert; // ohne Klammern, die Funktion soll ja nicht aufgerufen werden.

myArray[0].apply(this, ['Hallo Welt']); // = alert('Hallo Welt');
 

mrBrown

Super-Moderator
Mitarbeiter
Weil du die Funktion ausgeben lässt, und nicht das Ergebnis dieser Funktion.
Um das Ergebnis zu bekommen, musst du sie explizit aufrufen (zb mit array[0]())
 

Neue Themen


Oben