Back to blog
Jun 2018·1 min read

Javascript Snippets

#javascript#snippets

Hier sammle ich ein paar JavaScript-Snippets. Eine Liste, die im Laufe der Zeit sicher noch erweitert wird :)

Zufälliges Element aus einem Array? Nichts leichter als das!

var items = [123, 'John', 11111, 'Doe', 'foo', 2924, 'bar', 'foobar', 55, 'baz'];
var randomItem = items[Math.floor(Math.random() * items.length)];

Zufällige Zahl mit einem Mindest- und einem Maximalwert? Here you go!

var x = Math.floor(Math.random() * (max - min + 1)) + min;

Ein "SO-Fundstück": Javascript shorthand if/else. Wusste nicht dass das möglich ist. Sehr mächtige Sprache... :D

var y = (x == 2 ? "yes" : "no");

Quelle: stackoverflow.com/questions/11069278

Optionale Parameter

if (typeof optionalArg === 'undefined') {
  optionalArg = 'default';
}

Promise

new Promise(function(resolve, reject) {
  alert("Aktion 1");
  resolve();
}).then(function() {
  alert("Aktion 1 beendet");
});
NewerScrollblurOlderBash Snippets