diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:15 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:15 -0500 |
commit | 4b1a9203c547c019fc5398082ae19a3f3d4c3efe (patch) | |
tree | d4a40e13ceeb9f85479605110a76e7a4d5f3b56b /files/de/learn/javascript/first_steps | |
parent | 33058f2b292b3a581333bdfb21b8f671898c5060 (diff) | |
download | translated-content-4b1a9203c547c019fc5398082ae19a3f3d4c3efe.tar.gz translated-content-4b1a9203c547c019fc5398082ae19a3f3d4c3efe.tar.bz2 translated-content-4b1a9203c547c019fc5398082ae19a3f3d4c3efe.zip |
initial commit
Diffstat (limited to 'files/de/learn/javascript/first_steps')
6 files changed, 2184 insertions, 0 deletions
diff --git a/files/de/learn/javascript/first_steps/erster_blick/index.html b/files/de/learn/javascript/first_steps/erster_blick/index.html new file mode 100644 index 0000000000..e772147cae --- /dev/null +++ b/files/de/learn/javascript/first_steps/erster_blick/index.html @@ -0,0 +1,597 @@ +--- +title: Ein erster Eindruck von JavaScript +slug: Learn/JavaScript/First_steps/Erster_Blick +translation_of: Learn/JavaScript/First_steps/A_first_splash +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps")}}</div> + +<p class="summary">Nachdem Sie etwas über die Theorie von JavaScript gelernt haben und was Sie damit machen können, werden wir Ihnen in einem komplett praktischen Tutorial einen Crashkurs in den Grundfunktionen von JavaScript anbieten. Wir werden hier Schritt für Schritt ein einfaches Zahlenraten Spiel programmieren.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Voraussetzungen:</th> + <td>Grundlegende Computerkenntnisse, einfache Grundkentnisse von HTML und CSS, sowie eine Vorstellung, was JavaScript ist.</td> + </tr> + <tr> + <th scope="row">Ziel:</th> + <td>Erste Erfahrung beim Schreiben von JavaScript zu bekommen und zumindest ein grundlegendes Verständnis dafür zu erlangen, was das Schreiben eines JavaScript-Programms beinhaltet.</td> + </tr> + </tbody> +</table> + +<p>Es ist nicht nötig, dass Sie den gesamten Code sofort im Detail verstehen - wir wollen Ihnen nur grob die Konzepte vorab vorstellen und Ihnen eine Vorstellung davon vermitteln, wie JavaScript (und andere Programmiersprachen) funktionieren. In den folgenden Artikeln werden wir alle diese Funktionen noch einmal im Detail besprechen!</p> + +<div class="note"> +<p>Hinweis: Viele der Befehle und Konstrukte, die Sie in JavaScript sehen werden, sind die gleichen wie in anderen Programmiersprachen - Funktionen, Schleifen, etc. Die Syntax sieht anders aus, aber die Konzepte sind immer noch weitgehend die gleichen.</p> +</div> + +<h2 id="Denken_wie_ein_Programmierer">Denken wie ein Programmierer</h2> + +<p>Eines der schwierigsten Dinge, die man bei der Programmierung lernen muss, sind nicht die Befehle, sondern wie man sie zur Lösung der Aufgabe anwendet. Sie müssen anfangen, wie ein Programmierer zu denken - Sie müssen sich im klaren sein was Ihr Programm tun soll, um dann herauszuarbeiten welche Funktionen und Befehle Sie dafür benötigen.</p> + +<p>Dies erfordert eine Mischung aus harter Arbeit, Erfahrung mit der Programmiersprache und Praxis - und ein wenig Kreativität. Je mehr Sie kodieren, desto besser werden Sie werden. Wir können nicht versprechen, dass Sie in fünf Minuten ein "Programmierer-Gehirn" entwickeln werden, aber wir werden Ihnen viel Gelegenheit geben, während des gesamten Kurses das Denken wie ein Programmierer zu üben.</p> + +<p>In diesem Sinne betrachten Sie das Beispiel, das wir in diesem Artikel erstellen werden und üben damit den Prozess der Zerlegung in konkrete Einzelschritte.</p> + +<h2 id="Beispiel_—_Rate_die_Zahl">Beispiel — Rate die Zahl</h2> + +<p>In diesem Artikel zeigen wir Ihnen, wie Sie das Ratespiel aufbauen können, das Sie hier sehen können.:</p> + +<div class="hidden"> +<h6 id="Top_hidden_code">Top hidden code</h6> + +<pre class="brush: html"><!DOCTYPE html> +<html> + +<head> + <meta charset="utf-8"> + <title>Number guessing game</title> + <style> + html { + font-family: sans-serif; + } + + body { + width: 50%; + max-width: 800px; + min-width: 480px; + margin: 0 auto; + } + + .lastResult { + color: white; + padding: 3px; + } + </style> +</head> + +<body> + <h1>Zahlenraten</h1> + <p>Wir haben eine Zufallszahl zwischen 1 und 100 gewählt. Können Sie sie in höchstens 10 Versuchen erraten? Nach jeder Eingabe bekommen Sie einen Hinweis ob ihre Zahl zu gross oder zu klein war</p> + <div class="form"> <label for="guessField">Geben Sie ihre Zahl ein: </label><input type="text" id="guessField" class="guessField"> <input type="submit" value="Tip absenden" class="guessSubmit"> </div> + <div class="resultParas"> + <p class="guesses"></p> + <p class="lastResult"></p> + <p class="lowOrHi"></p> + </div> +<script> + // Ihr JavaScript Code steht hier + let randomNumber = Math.floor(Math.random() * 100) + 1; + const guesses = document.querySelector('.guesses'); + const lastResult = document.querySelector('.lastResult'); + const lowOrHi = document.querySelector('.lowOrHi'); + const guessSubmit = document.querySelector('.guessSubmit'); + const guessField = document.querySelector('.guessField'); + let guessCount = 1; + let resetButton; + + function checkGuess() { + let userGuess = Number(guessField.value); + if (guessCount === 1) { + guesses.textContent = 'Vorherige Versuche: '; + } + + guesses.textContent += userGuess + ' '; + + if (userGuess === randomNumber) { + lastResult.textContent = 'Glückwunsch! Richtig geraten!'; + lastResult.style.backgroundColor = 'green'; + lowOrHi.textContent = ''; + setGameOver(); + } else if (guessCount === 10) { + lastResult.textContent = '!!!ENDESPIEL!!!'; + lowOrHi.textContent = ''; + setGameOver(); + } else { + lastResult.textContent = 'Falsch!'; + lastResult.style.backgroundColor = 'red'; + if(userGuess < randomNumber) { + lowOrHi.textContent = 'Ihre Zahl ist zu niedrig!' ; + } else if(userGuess > randomNumber) { + lowOrHi.textContent = 'Ihre Zahl ist zu hoch!'; + } + } + + guessCount++; + guessField.value = ''; + } + + guessSubmit.addEventListener('click', checkGuess); + + function setGameOver() { + guessField.disabled = true; + guessSubmit.disabled = true; + resetButton = document.createElement('button'); + resetButton.textContent = 'Spiel neu starten'; + document.body.appendChild(resetButton); + resetButton.addEventListener('click', resetGame); + } + + function resetGame() { + guessCount = 1; + const resetParas = document.querySelectorAll('.resultParas p'); + for(let i = 0 ; i < resetParas.length ; i++) { + resetParas[i].textContent = ''; + } + + resetButton.parentNode.removeChild(resetButton); + guessField.disabled = false; + guessSubmit.disabled = false; + guessField.value = ''; + guessField.focus(); + lastResult.style.backgroundColor = 'white'; + randomNumber = Math.floor(Math.random() * 100) + 1; + } +</script> + +</body> +</html></pre> +</div> + +<p>{{ EmbedLiveSample('Top_hidden_code', '100%', 320, "", "", "hide-codepen-jsfiddle") }}</p> + +<p>Machen Sie sich mit der Funktionsweise des Spiels vertraut, bevor Sie weitermachen.</p> + +<p>Stellen wir uns vor, Ihr Chef hat Ihnen den folgenden Auftrag für die Erstellung dieses Spiels gegeben:</p> + +<blockquote> +<p>Schreiben Sie ein Programm das ein Zahlenratespiel implementiert. Es sollte eine Zufallszahl zwischen 1 und 100 wählen und den Spieler auffordern, die Zahl nach spätestens 10 Runden zu erraten. Nach jedem Zug sollte dem Spieler mitgeteilt werden, ob er richtig geraten hat oder nicht - und, wenn er Unrecht hat, ob die Zahl zu niedrig oder zu hoch war. Außerdem sollen dem Spieler alle vorher geratenen Zahlen angezeigt werden. Das Spiel endet, wenn der Spieler richtig rät oder wenn er 10-mal falsch geraten hat. Wenn das Spiel endet, sollte dem Spieler die Möglichkeit gegeben werden, erneut zu spielen.</p> +</blockquote> + +<p>Wenn wir uns diesen Anweisungen ansehen, können wir zunächst damit beginnen, ihn in einfache, umsetzbare Aufgaben aufzuteilen, und zwar aus der Sicht eines Programmierers:</p> + +<ol> + <li>Generiere eine zufällige Zahl zwischen 1 und 100.</li> + <li>Speichere die Anzahl der getätigten Rateversuche, setze den Wert anfangs auf 1.</li> + <li>Ermögliche dem Spieler, einen Tipp abzugeben.</li> + <li>Sobald ein Tip abgegeben wurde, speichere sie damit der Spieler seine vorherigen Eingaben sehen kann.</li> + <li>Als Nächstes überprüfe, ob es sich um die richtige Zahl handelt.</li> + <li>Wenn sie richtig ist: + <ol> + <li>Zeige Glückwunsch Nachricht.</li> + <li>Verhindere weiter Eingaben, da das Spiel zu Ende ist.</li> + <li>Biete eine Möglichkeit, das Spiel neu zu starten.</li> + </ol> + </li> + <li>Wenn sie falsch ist und noch Versuche übrig sind: + <ol> + <li>Dem Spieler mitteilen, dass die Zahl noch nicht erraten ist.</li> + <li>Die Eingabe einer weiteren Zahl ermöglichen.</li> + <li>Die Anzahl der Rateversuche um 1 erhöhen.</li> + </ol> + </li> + <li>Wenn die Zahl falsch ist und keine Versuche mehr übrig sind: + <ol> + <li>Dem Spieler mitteilen, dass das Spiel zu Ende ist.</li> + <li>Keine weiteren Eingaben mehr zulassen.</li> + <li>Ein Steuerelement zum Neustart des Spiels anzeigen.</li> + </ol> + </li> + <li>Wenn das Spiel neu startet, sicherstellen dass Logik und Benutzeroberfläche zurückgesetzt werden. Danach zurück zum 1. Schritt.</li> +</ol> + +<p>Lassen Sie uns nun fortfahren und schauen, wie wir diese Punkte in Code umwandeln können, das Beispiel aufbauen und die JavaScript-Funktionen während der Arbeit erforschen.</p> + +<h3 id="Vorbereitungen">Vorbereitungen</h3> + +<p>Um dieses Tutorial zu beginnen, möchten wir Sie bitten, eine lokale Kopie der Datei <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/first-splash/number-guessing-game-start.html">number-guessing-game-start.html</a> (<a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/first-splash/number-guessing-game-start.html">see it live here</a>) zu erstellen. Öffnen Sie es sowohl in Ihrem Texteditor als auch in Ihrem Webbrowser. Im Moment sehen Sie eine einfache Überschrift, einen Absatz mit Anweisungen und ein Formular zur Eingabe einer Schätzung, aber das Formular wird derzeit nichts tun.</p> + +<p>Unseren gesamten Code werden wir innerhalb des {{htmlelement("script")}} Elements am Ende der HTML-Datei einfügen:</p> + +<pre class="brush: html"><script> + + // Ihr Programm steht hier + +</script> +</pre> + +<h3 id="Variablen_hinzufügen_um_Daten_zu_speichern">Variablen hinzufügen um Daten zu speichern</h3> + +<p>Lassen Sie uns anfangen. Fügen Sie zunächst die folgenden Zeilen nach dem {{htmlelement("script")}} Element ein:</p> + +<pre class="brush: js">let randomNumber = Math.floor(Math.random() * 100) + 1; + +const guesses = document.querySelector('.guesses'); +const lastResult = document.querySelector('.lastResult'); +const lowOrHi = document.querySelector('.lowOrHi'); + +const guessSubmit = document.querySelector('.guessSubmit'); +const guessField = document.querySelector('.guessField'); + +let guessCount = 1; +let resetButton;</pre> + +<p>Obiger Code richtet die Variablen und Konstanten ein, die wir benötigen, um die Daten zu speichern, die unser Programm verwenden wird. Variablen sind im Grunde genommen Container für Werte (z.B. Zahlen oder Text). Sie erstellen eine Variable mit dem Schlüsselwort <code>let</code> (oder <code>var</code>) gefolgt von einem Namen für Ihre Variable (Sie werden mehr über den Unterschied zwischen den beiden Schlüsselwörtern in einem zukünftigen Artikel lesen). Konstanten werden verwendet, um Werte zu speichern, die Sie nicht ändern möchten, und werden mit dem Schlüsselwort const erstellt. In diesem Fall verwenden wir Konstanten, um Referenzen auf Teile unserer Benutzeroberfläche zu speichern; der Text in einigen von ihnen kann sich ändern, aber die referenzierten HTML-Elemente bleiben unverändert.</p> + +<p>Sie können Ihrer Variablen oder Konstanten einen Wert mit einem Gleichheitszeichen (=) zuweisen, gefolgt von dem Wert, den Sie ihr geben möchten.</p> + +<p>In unser Beispiel:</p> + +<ul> + <li>Die erste Variable — <code>randomNumber</code> — ist assigned a random number between 1 and 100, calculated using a mathematical algorithm.</li> + <li>The first three constants are each made to store a reference to the results paragraphs in our HTML, and are used to insert values into the paragraphs later on in the code: + <pre class="brush: html"><p class="guesses"></p> +<p class="lastResult"></p> +<p class="lowOrHi"></p></pre> + </li> + <li>The next two constants store references to the form text input and submit button and are used to control submitting the guess later on. + <pre class="brush: html"><label for="guessField">Enter a guess: </label><input type="text" id="guessField" class="guessField"> +<input type="submit" value="Submit guess" class="guessSubmit"></pre> + </li> + <li>Our final two variables store a guess count of 1 (used to keep track of how many guesses the player has had), and a reference to a reset button that doesn't exist yet (but will later).</li> +</ul> + +<div class="note"> +<p><strong>Note</strong>: You'll learn a lot more about variables/constants later on in the course, starting with the <a href="https://developer.mozilla.org/en-US/docs/user:chrisdavidmills/variables">next article</a>.</p> +</div> + +<h3 id="Functions">Functions</h3> + +<p>Next, add the following below your previous JavaScript:</p> + +<pre class="brush: js">function checkGuess() { + alert('I am a placeholder'); +}</pre> + +<p>Functions are reusable blocks of code that you can write once and run again and again, saving the need to keep repeating code all the time. This is really useful. There are a number of ways to define functions, but for now we'll concentrate on one simple type. Here we have defined a function by using the keyword <code>function</code>, followed by a name, with parentheses put after it. After that we put two curly braces (<code>{ }</code>). Inside the curly braces goes all the code that we want to run whenever we call the function.</p> + +<p>When we want to run the code, we type the name of the function followed by the parentheses.</p> + +<p>Let's try that now. Save your code and refresh the page in your browser. Then go into the <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">developer tools JavaScript console</a>, and enter the following line:</p> + +<pre class="brush: js">checkGuess();</pre> + +<p>After pressing <kbd>Return</kbd>/<kbd>Enter</kbd>, you should see an alert come up that says "<samp>I am a placeholder</samp>"; we have defined a function in our code that creates an alert whenever we call it.</p> + +<div class="note"> +<p><strong>Note</strong>: You'll learn a lot more about functions <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">later in the course</a>.</p> +</div> + +<h3 id="Operators">Operators</h3> + +<p>JavaScript operators allow us to perform tests, do maths, join strings together, and other such things.</p> + +<p>If you haven't already done so, save your code, refresh the page in your browser, and open the <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">developer tools JavaScript console</a>. Then we can try typing in the examples shown below — type in each one from the "Example" columns exactly as shown, pressing <kbd>Return</kbd>/<kbd>Enter</kbd> after each one, and see what results they return.</p> + +<p>First let's look at arithmetic operators, for example:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Operator</th> + <th scope="col">Name</th> + <th scope="col">Example</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>+</code></td> + <td>Addition</td> + <td><code>6 + 9</code></td> + </tr> + <tr> + <td><code>-</code></td> + <td>Subtraction</td> + <td><code>20 - 15</code></td> + </tr> + <tr> + <td><code>*</code></td> + <td>Multiplication</td> + <td><code>3 * 7</code></td> + </tr> + <tr> + <td><code>/</code></td> + <td>Division</td> + <td><code>10 / 5</code></td> + </tr> + </tbody> +</table> + +<p>You can also use the <code>+</code> operator to join text strings together (in programming, this is called <em>concatenation</em>). Try entering the following lines, one at a time:</p> + +<pre class="brush: js">let name = 'Bingo'; +name; +let hello = ' says hello!'; +hello; +let greeting = name + hello; +greeting;</pre> + +<p>There are also some shortcut operators available, called augmented <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">assignment operators</a>. For example, if you want to simply add a new text string to an existing one and return the result, you could do this:</p> + +<pre class="brush: js">name += ' says hello!';</pre> + +<p>This is equivalent to</p> + +<pre class="brush: js">name = name + ' says hello!';</pre> + +<p>When we are running true/false tests (for example inside conditionals — see {{anch("Conditionals", "below")}}) we use <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">comparison operators</a>. For example:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Operator</th> + <th scope="col">Name</th> + <th scope="col">Example</th> + </tr> + <tr> + <td><code>===</code></td> + <td>Strict equality (is it exactly the same?)</td> + <td> + <pre class="brush: js"> +5 === 2 + 4 // false +'Chris' === 'Bob' // false +5 === 2 + 3 // true +2 === '2' // false; number versus string +</pre> + </td> + </tr> + <tr> + <td><code>!==</code></td> + <td>Non-equality (is it not the same?)</td> + <td> + <pre class="brush: js"> +5 !== 2 + 4 // true +'Chris' !== 'Bob' // true +5 !== 2 + 3 // false +2 !== '2' // true; number versus string +</pre> + </td> + </tr> + <tr> + <td><code><</code></td> + <td>Less than</td> + <td> + <pre class="brush: js"> +6 < 10 // true +20 < 10 // false</pre> + </td> + </tr> + <tr> + <td><code>></code></td> + <td>Greater than</td> + <td> + <pre class="brush: js"> +6 > 10 // false +20 > 10 // true</pre> + </td> + </tr> + </thead> +</table> + +<h3 id="Conditionals">Conditionals</h3> + +<p>Returning to our <code>checkGuess()</code> function, I think it's safe to say that we don't want it to just spit out a placeholder message. We want it to check whether a player's guess is correct or not, and respond appropriately.</p> + +<p>At this point, replace your current <code>checkGuess()</code> function with this version instead:</p> + +<pre class="brush: js">function checkGuess() { + let userGuess = Number(guessField.value); + if (guessCount === 1) { + guesses.textContent = 'Previous guesses: '; + } + guesses.textContent += userGuess + ' '; + + if (userGuess === randomNumber) { + lastResult.textContent = 'Congratulations! You got it right!'; + lastResult.style.backgroundColor = 'green'; + lowOrHi.textContent = ''; + setGameOver(); + } else if (guessCount === 10) { + lastResult.textContent = '!!!GAME OVER!!!'; + setGameOver(); + } else { + lastResult.textContent = 'Wrong!'; + lastResult.style.backgroundColor = 'red'; + if(userGuess < randomNumber) { + lowOrHi.textContent = 'Last guess was too low!'; + } else if(userGuess > randomNumber) { + lowOrHi.textContent = 'Last guess was too high!'; + } + } + + guessCount++; + guessField.value = ''; + guessField.focus(); +}</pre> + +<p>This is a lot of code — phew! Let's go through each section and explain what it does.</p> + +<ul> + <li>The first line (line 2 above) declares a variable called <code>userGuess</code> and sets its value to the current value entered inside the text field. We also run this value through the built-in <code>Number()</code> constructor, just to make sure the value is definitely a number.</li> + <li>Next, we encounter our first conditional code block (lines 3–5 above). A conditional code block allows you to run code selectively, depending on whether a certain condition is true or not. It looks a bit like a function, but it isn't. The simplest form of conditional block starts with the keyword <code>if</code>, then some parentheses, then some curly braces. Inside the parentheses we include a test. If the test returns <code>true</code>, we run the code inside the curly braces. If not, we don't, and move on to the next bit of code. In this case the test is testing whether the <code>guessCount</code> variable is equal to <code>1</code> (i.e. whether this is the player's first go or not): + <pre class="brush: js">guessCount === 1</pre> + If it is, we make the guesses paragraph's text content equal to "<samp>Previous guesses: </samp>". If not, we don't.</li> + <li>Line 6 appends the current <code>userGuess</code> value onto the end of the <code>guesses</code> paragraph, plus a blank space so there will be a space between each guess shown.</li> + <li>The next block (lines 8–24 above) does a few checks: + <ul> + <li>The first <code>if(){ }</code> checks whether the user's guess is equal to the <code>randomNumber</code> set at the top of our JavaScript. If it is, the player has guessed correctly and the game is won, so we show the player a congratulations message with a nice green color, clear the contents of the Low/High guess information box, and run a function called <code>setGameOver()</code>, which we'll discuss later.</li> + <li>Now we've chained another test onto the end of the last one using an <code>else if(){ }</code> structure. This one checks whether this turn is the user's last turn. If it is, the program does the same thing as in the previous block, except with a game over message instead of a congratulations message.</li> + <li>The final block chained onto the end of this code (the <code>else { }</code>) contains code that is only run if neither of the other two tests returns true (i.e. the player didn't guess right, but they have more guesses left). In this case we tell them they are wrong, then we perform another conditional test to check whether the guess was higher or lower than the answer, displaying a further message as appropriate to tell them higher or lower.</li> + </ul> + </li> + <li>The last three lines in the function (lines 26–28 above) get us ready for the next guess to be submitted. We add 1 to the <code>guessCount</code> variable so the player uses up their turn (<code>++</code> is an incrementation operation — increment by 1), and empty the value out of the form text field and focus it again, ready for the next guess to be entered.</li> +</ul> + +<h3 id="Events">Events</h3> + +<p>At this point we have a nicely implemented <code>checkGuess()</code> function, but it won't do anything because we haven't called it yet. Ideally we want to call it when the "Submit guess" button is pressed, and to do this we need to use an event. Events are things that happen in the browser — a button being clicked, a page loading, a video playing, etc. — in response to which we can run blocks of code. The constructs that listen out for the event happening are called <strong>event listeners</strong>, and the blocks of code that run in response to the event firing are called <strong>event handlers</strong>.</p> + +<p>Add the following line below your <code>checkGuess()</code> function:</p> + +<pre class="brush: js">guessSubmit.addEventListener('click', checkGuess);</pre> + +<p>Here we are adding an event listener to the <code>guessSubmit</code> button. This is a method that takes two input values (called <em>arguments</em>) — the type of event we are listening out for (in this case <code>click</code>) as a string, and the code we want to run when the event occurs (in this case the <code>checkGuess()</code> function). Note that we don't need to specify the parentheses when writing it inside {{domxref("EventTarget.addEventListener", "addEventListener()")}}.</p> + +<p>Try saving and refreshing your code now, and your example should work — to a point. The only problem now is that if you guess the correct answer or run out of guesses, the game will break because we've not yet defined the <code>setGameOver()</code> function that is supposed to be run once the game is over. Let's add our missing code now and complete the example functionality.</p> + +<h3 id="Finishing_the_game_functionality">Finishing the game functionality</h3> + +<p>Let's add that <code>setGameOver()</code> function to the bottom of our code and then walk through it. Add this now, below the rest of your JavaScript:</p> + +<pre class="brush: js">function setGameOver() { + guessField.disabled = true; + guessSubmit.disabled = true; + resetButton = document.createElement('button'); + resetButton.textContent = 'Start new game'; + document.body.appendChild(resetButton); + resetButton.addEventListener('click', resetGame); +}</pre> + +<ul> + <li>The first two lines disable the form text input and button by setting their disabled properties to <code>true</code>. This is necessary, because if we didn't, the user could submit more guesses after the game is over, which would mess things up.</li> + <li>The next three lines generate a new {{htmlelement("button")}} element, set its text label to "Start new game", and add it to the bottom of our existing HTML.</li> + <li>The final line sets an event listener on our new button so that when it is clicked, a function called <code>resetGame()</code> is run.</li> +</ul> + +<p>Now we need to define this function too! Add the following code, again to the bottom of your JavaScript:</p> + +<pre class="brush: js">function resetGame() { + guessCount = 1; + + const resetParas = document.querySelectorAll('.resultParas p'); + for (let i = 0 ; i < resetParas.length ; i++) { + resetParas[i].textContent = ''; + } + + resetButton.parentNode.removeChild(resetButton); + + guessField.disabled = false; + guessSubmit.disabled = false; + guessField.value = ''; + guessField.focus(); + + lastResult.style.backgroundColor = 'white'; + + randomNumber = Math.floor(Math.random() * 100) + 1; +}</pre> + +<p>This rather long block of code completely resets everything to how it was at the start of the game, so the player can have another go. It:</p> + +<ul> + <li>Puts the <code>guessCount</code> back down to 1.</li> + <li>Empties all the text out of the information paragraphs.</li> + <li>Removes the reset button from our code.</li> + <li>Enables the form elements, and empties and focuses the text field, ready for a new guess to be entered.</li> + <li>Removes the background color from the <code>lastResult</code> paragraph.</li> + <li>Generates a new random number so that you are not just guessing the same number again!</li> +</ul> + +<p><strong>At this point you should have a fully working (simple) game — congratulations!</strong></p> + +<p>All we have left to do now in this article is talk about a few other important code features that you've already seen, although you may have not realized it.</p> + +<h3 id="Loops">Loops</h3> + +<p>One part of the above code that we need to take a more detailed look at is the <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a> loop. Loops are a very important concept in programming, which allow you to keep running a piece of code over and over again, until a certain condition is met.</p> + +<p>To start with, go to your <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">browser developer tools JavaScript console</a> again, and enter the following:</p> + +<pre class="brush: js">for (let i = 1 ; i < 21 ; i++) { console.log(i) }</pre> + +<p>What happened? The numbers <samp>1</samp> to <samp>20</samp> were printed out in your console. This is because of the loop. A <code>for</code> loop takes three input values (arguments):</p> + +<ol> + <li><strong>A starting value</strong>: In this case we are starting a count at 1, but this could be any number you like. You could replace the letter <code>i</code> with any name you like too, but <code>i</code> is used as a convention because it's short and easy to remember.</li> + <li><strong>An exit condition</strong>: Here we have specified <code>i < 21</code> — the loop will keep going until <code>i</code> is no longer less than 21. When <code>i</code> reaches 21, the loop will no longer run.</li> + <li><strong>An incrementor</strong>: We have specified <code>i++</code>, which means "add 1 to i". The loop will run once for every value of <code>i</code>, until <code>i</code> reaches a value of 21 (as discussed above). In this case, we are simply printing the value of <code>i</code> out to the console on every iteration using {{domxref("Console.log", "console.log()")}}.</li> +</ol> + +<p>Now let's look at the loop in our number guessing game — the following can be found inside the <code>resetGame()</code> function:</p> + +<pre class="brush: js">let resetParas = document.querySelectorAll('.resultParas p'); +for (let i = 0 ; i < resetParas.length ; i++) { + resetParas[i].textContent = ''; +}</pre> + +<p>This code creates a variable containing a list of all the paragraphs inside <code><div class="resultParas"></code> using the {{domxref("Document.querySelectorAll", "querySelectorAll()")}} method, then it loops through each one, removing the text content of each.</p> + +<h3 id="A_small_discussion_on_objects">A small discussion on objects</h3> + +<p>Let's add one more final improvement before we get to this discussion. Add the following line just below the <code>let resetButton;</code> line near the top of your JavaScript, then save your file:</p> + +<pre class="brush: js">guessField.focus();</pre> + +<p>This line uses the {{domxref("HTMLElement.focus", "focus()")}} method to automatically put the text cursor into the {{htmlelement("input")}} text field as soon as the page loads, meaning that the user can start typing their first guess right away, without having to click the form field first. It's only a small addition, but it improves usability — giving the user a good visual clue as to what they've got to do to play the game.</p> + +<p>Let's analyze what's going on here in a bit more detail. In JavaScript, everything is an object. An object is a collection of related functionality stored in a single grouping. You can create your own objects, but that is quite advanced and we won't be covering it until much later in the course. For now, we'll just briefly discuss the built-in objects that your browser contains, which allow you to do lots of useful things.</p> + +<p>In this particular case, we first created a <code>guessField</code> constant that stores a reference to the text input form field in our HTML — the following line can be found amongst our declarations near the top of the code:</p> + +<pre class="brush: js">const guessField = document.querySelector('.guessField');</pre> + +<p>To get this reference, we used the {{domxref("document.querySelector", "querySelector()")}} method of the {{domxref("document")}} object. <code>querySelector()</code> takes one piece of information — a <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors">CSS selector</a> that selects the element you want a reference to.</p> + +<p>Because <code>guessField</code> now contains a reference to an {{htmlelement("input")}} element, it will now have access to a number of properties (basically variables stored inside objects, some of which can't have their values changed) and methods (basically functions stored inside objects). One method available to input elements is <code>focus()</code>, so we can now use this line to focus the text input:</p> + +<pre class="brush: js">guessField.focus();</pre> + +<p>Variables that don't contain references to form elements won't have <code>focus()</code> available to them. For example, the <code>guesses</code> constant contains a reference to a {{htmlelement("p")}} element, and the <code>guessCount</code> variable contains a number.</p> + +<h3 id="Playing_with_browser_objects">Playing with browser objects</h3> + +<p>Let's play with some browser objects a bit.</p> + +<ol> + <li>First of all, open up your program in a browser.</li> + <li>Next, open your <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">browser developer tools</a>, and make sure the JavaScript console tab is open.</li> + <li>Type in <code>guessField</code> and the console will show you that the variable contains an {{htmlelement("input")}} element. You'll also notice that the console autocompletes the names of objects that exist inside the execution environment, including your variables!</li> + <li>Now type in the following: + <pre class="brush: js">guessField.value = 'Hello';</pre> + The <code>value</code> property represents the current value entered into the text field. You'll see that by entering this command, we've changed the text in the text field!</li> + <li>Now try typing in <code>guesses</code> and pressing return. The console will show you that the variable contains a {{htmlelement("p")}} element.</li> + <li>Now try entering the following line: + <pre class="brush: js">guesses.value</pre> + The browser will return <code>undefined</code>, because paragraphs don't have the <code>value</code> property.</li> + <li>To change the text inside a paragraph, you need the {{domxref("Node.textContent", "textContent")}} property instead. Try this: + <pre class="brush: js">guesses.textContent = 'Where is my paragraph?';</pre> + </li> + <li>Now for some fun stuff. Try entering the below lines, one by one: + <pre class="brush: js">guesses.style.backgroundColor = 'yellow'; +guesses.style.fontSize = '200%'; +guesses.style.padding = '10px'; +guesses.style.boxShadow = '3px 3px 6px black';</pre> + Every element on a page has a <code>style</code> property, which itself contains an object whose properties contain all the inline CSS styles applied to that element. This allows us to dynamically set new CSS styles on elements using JavaScript.</li> +</ol> + +<h2 id="Finished_for_now...">Finished for now...</h2> + +<p>So that's it for building the example. You got to the end — well done! Try your final code out, or <a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/first-splash/number-guessing-game.html">play with our finished version here</a>. If you can't get the example to work, check it against the <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/first-splash/number-guessing-game.html">source code</a>.</p> + +<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript">What is JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/A_first_splash">A first splash into JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables">Storing the information you need — Variables</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math">Basic math in JavaScript — numbers and operators</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Assessment: Silly story generator</a></li> +</ul> diff --git a/files/de/learn/javascript/first_steps/index.html b/files/de/learn/javascript/first_steps/index.html new file mode 100644 index 0000000000..092a419e14 --- /dev/null +++ b/files/de/learn/javascript/first_steps/index.html @@ -0,0 +1,67 @@ +--- +title: Erste Schritte mit JavaScript +slug: Learn/JavaScript/First_steps +tags: + - Anleitung + - Arrays + - Artikel + - Aufgaben + - Einsteiger + - Felder + - JavaScript + - Landing + - Lernmodul + - Mathematik + - Operatoren + - Variablen + - Zahlen + - Zeichenketten +translation_of: Learn/JavaScript/First_steps +--- +<div>{{LearnSidebar}}</div> + +<p class="summary">In unserem ersten Lernmodul zu JavaScript beantworten wir grundlegende Fragen wie »Was ist JavaScript?«, »Wie sieht es aus?« und »Was kann es?«, bevor wir Sie bei Ihren ersten praktischen Erfahrungen mit JavaScript begleiten. Danach erklären wir einige der wichtigsten Bausteine – wie etwa Variablen, Zeichenketten, Zahlen und Felder – im Detail.</p> + +<h2 id="Voraussetzungen">Voraussetzungen</h2> + +<p>Um mit diesem Lernmodul zu beginnen, brauchen Sie keinerlei Vorwissen in Sachen JavaScript – Sie sollten aber bereits ein wenig mit HTML und CSS vertraut sein. Wir raten Ihnen daher dazu, die folgendenen Lektionen durchzuarbeiten, bevor Sie mit JavaScript loslegen:</p> + +<ul> + <li><a href="https://developer.mozilla.org/de/docs/Learn/Getting_started_with_the_web">Lerne das Internet kennen</a> (inklusive einer wirklich <a href="/de/docs/Learn/Getting_started_with_the_web/JavaScript_basics">grundlegenden Einführung in JavaScript</a>).</li> + <li><a href="/de/docs/Learn/HTML/Introduction_to_HTML">Einführung in HTML</a>.</li> + <li><a href="/de/docs/Learn/CSS/Introduction_to_CSS">Einführung in CSS</a>.</li> +</ul> + +<div class="note"> +<p><strong>Anmerkung</strong>: Falls Sie auf einem Computer, einem Tablet oder sonstigem Gerät arbeiten, auf dem Sie keine eigenen Dateien anlegen können, können Sie die Codebeispiele meist auch in einer Online-Coding-Umgebung wie <a href="http://jsbin.com/">JSBin</a> oder <a href="https://thimble.mozilla.org/">Thimble</a> ausprobieren.</p> +</div> + +<h2 id="Anleitungen">Anleitungen</h2> + +<dl> + <dt><a href="/de/docs/Learn/JavaScript/First_steps/What_is_JavaScript">Was ist JavaScript?</a></dt> + <dd>Willkommen beim MDN-Einsteigerkurs zu JavaScript! In diesem ersten Artikel betrachten wir JavaScript von außen, beantworten Fragen wie »Was ist das?« und »Was macht es?«, und machen Sie mit dem Zweck von JavaScript vertraut.</dd> + <dt><a href="/de/docs/Learn/JavaScript/First_steps/A_first_splash">Ein erster Abstecher zu JavaScript</a></dt> + <dd>Jetzt, da Sie ein wenig Hintergrundwissen über JavaScript und das, was Sie damit anstellen können haben, werden wir Ihnen in einem Crashkurs die wichtigsten Features von JavaScript anhand praktischer Beispiele beibringen.</dd> + <dt><a href="/de/docs/Learn/JavaScript/First_steps/What_went_wrong">Was lief verkehrt? JavaScript-Probleme beheben</a></dt> + <dd>Nachdem Sie im vorherigen Artikel das Spiel »Zahlen-Raten« konstruiert hatten, kann es sein, dass Sie feststellen mussten, dass es nicht funktionierte. Keine Angst – dieser Artikel soll Sie davor retten, sich wegen solcher Probleme die Haare zu raufen, indem er Ihnen einige einfache Tipps dazu gibt, wie Sie Fehler in JavaScript-Programmen finden und beheben.</dd> + <dt><a href="/de/docs/Learn/JavaScript/First_steps/Variables">Informationen, die Sie brauchen, speichern – Variablen</a></dt> + <dd>Nach dem Lesen der letzten paar Artikel sollten Sie nun wissen, was JavaScript ist, was es für Sie tun kann, wie Sie es in Kombination mit anderen Web-Technologien einsetzen, und wie die wichtigsten Features in etwa aussehen. In diesem Artikel werden wir uns anschauen, wie man einen der grundlegendsten Bausteine von JavaScript verwendet – Variablen.</dd> + <dt><a href="/de/docs/Learn/JavaScript/First_steps/Math">Einfache Mathematik in JavaScript – Zahlen und Operatoren</a></dt> + <dd>An dieser Stelle im Kurs erörtern wir Mathematik in JavaScript – wie wir Operatoren und andere Features verwenden können, um Zahlen erfolgreich dazu zu bringen, zu tun, was wir wollen.</dd> + <dt><a href="/de/docs/Learn/JavaScript/First_steps/Strings">Text verarbeiten – Zeichenketten in JavaScript</a></dt> + <dd>Als Nächstes richten wir unsere Aufmerksamkeit auf Zeichenketten – so nennt man Textschnippsel in der Programmierung. In diesem Artikel werden wir uns häufig benötigtes Wissen zu Zeichenketten ansehen, etwa wie man sie erstellt, wie man Anführungszeichen in Zeichenketten maskiert und wie man Zeichenketten aneinanderhängt.</dd> + <dt><a href="/de/docs/Learn/JavaScript/First_steps/Useful_string_methods">Nützliche Zeichenketten-Methoden</a></dt> + <dd>Nachdem wir uns jetzt die Grundlagen von Zeichenketten angeeignet haben, schalten wir einen Gang hoch und überlegen uns, welche nützlichen Operationen wir mit den eingebauten Methoden auf Zeichenketten ausführen können: die Länge einer Zeichenkette festellen, Zeichenketten verknüpfen und aufteilen, ein Zeichen in einer Zeichenkette durch ein anderes ersetzen, und weitere.</dd> + <dt><a href="/de/docs/Learn/JavaScript/First_steps/Arrays">Felder</a></dt> + <dd>Im letzten Artikel dieses Lernmoduls betrachten wir Felder – ein sauberer Weg, um eine Liste von Datenelementen unter einem einzigen Variablennamen abzulegen. Wir schauen uns an, warum das nützlich ist, und erforschen dann, wie man ein Feld anlegt, Elemente, die darin gespeichert sind, abruft, hinzufügt und entfernt, und vieles mehr.</dd> +</dl> + +<h2 id="Aufgaben">Aufgaben</h2> + +<p>Die folgenden Aufgaben werden Ihr Verständnis der JavaScript-Grundlagen aus den vorherigen Anleitungen überprüfen.</p> + +<dl> + <dt><a href="/de/docs/Learn/JavaScript/First_steps/Silly_story_generator">Lustige Geschichten erzeugen</a></dt> + <dd>In dieser Aufgabe sollen Sie einen Teil des Wissens, das Sie erworben haben, einsetzen, um eine spaßige Anwendung zu entwickeln, die zufällige, lustige Geschichten erzeugt. Viel Spaß!</dd> +</dl> diff --git a/files/de/learn/javascript/first_steps/lustige_geschichten_generator/index.html b/files/de/learn/javascript/first_steps/lustige_geschichten_generator/index.html new file mode 100644 index 0000000000..1703f9b6a7 --- /dev/null +++ b/files/de/learn/javascript/first_steps/lustige_geschichten_generator/index.html @@ -0,0 +1,139 @@ +--- +title: Der Lustige Geschichten Generator +slug: Learn/JavaScript/First_steps/lustige_geschichten_generator +translation_of: Learn/JavaScript/First_steps/Silly_story_generator +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}</div> + +<p class="summary">In dieser Prüfung ist es deine Aufgabe das von dir in den vorherigen Artikeln gesammelten Wissen anzuwenden, indem due eine lustige Applikation schreibst, mit der man lustige Geschichten erzeugen kann. Viel Spass mit dem Lustige Geschichten Generator !</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Vorraussetzungen:</th> + <td>Bevor du dich an dieser Aufgabe versuchst, solltest du alle anderen Artikel dieses Moduls gelesen und bearbeitet haben.</td> + </tr> + <tr> + <th scope="row">Ziel:</th> + <td>Verständnis von fundamentalen JavaScript Kenntnissen, wie Variablen, Operatoren und einfachen Datentypen (Zahlen, Zeichenketten, Arrays)</td> + </tr> + </tbody> +</table> + +<h2 id="Start">Start</h2> + +<p>Um mit deiner Aufgabe zu beginnen, solltest du::</p> + +<ul> + <li>Öffne <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/assessment-start/index.html">die HTML-Vorlage</a> und speichere eine lokale Kopie davon auf deinem Rechner in einen neuen Ordner als <code>index.html</code>. Die Datei enthält auch einige CSS-Anweisungen für das Styling.</li> + <li>Öffne <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/assessment-start/raw-text.txt">die Seite, die die Text-Vorlagen enthält</a> und öffne sie in einem seperaten Browserfenster oder -tab. Die brauchst du später noch.</li> +</ul> + +<div class="note"> +<p><strong>Notiz</strong>: Alternativ kannst du auch eine Seite wie <a href="http://jsbin.com/">JSBin</a> oder <a href="https://glitch.com/">Glitch</a> benutzen, um die Aufgabe zu bearbeiten. Kopiere dazu einfach den Quelltext von HTML, CSS und JavaScript in einen dieser Online-Editoren. Wenn einer dieser Editoren kein extra JavaScript Panel haben sollte, kopiere das JavaScript einfach zwischen <code><script>-Tags</code> in deinem HTML-Code.</p> +</div> + +<h2 id="Projektbeschreibung">Projektbeschreibung</h2> + +<p>Für diese Aufgabe geben wir dir einige HTML/CSS Codestücke, einige Textbausteine und ein paar JavaScript Funktionen in die Hand; du musst die fehlenden JavaScript-Teile ergänzen, um alles zu einem lauffähigen Programm zu kombinieren, was Folgendes tun kann:</p> + +<ul> + <li>es generiert eine lustige Geschichte, wenn der "Generate random story" button gedrückt wird.</li> + <li>es ersetzt den vorgegebenen Namen "Bob" in der Geschichte mit einem individuellen Namen, allerdings nur, wenn eine Eingabe in das "Enter custom name" Text-Feld gemacht worden ist, bevor der Button gedrückt wurde.</li> + <li>es konvertiert US-amerikanische Maßeinheiten, wie Gewicht und Temperatur in die englischen Äquivalente, wenn der Radio-Button entsprechend gesetzt wurde, bevor der Button gedrückt wurde.</li> + <li>es generiert immer wieder eine neue Variante der Geschichte, wenn der Button erneut gedrückt wird.</li> +</ul> + +<p>Der folgende Screenshot zeigt dir ein Beispiel, wie die Ausgabe deines geschriebenen Programmes aussehen wird:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/16178/Screen_Shot_2018-09-19_at_10.01.38_AM.png" style="border-style: solid; border-width: 1px; display: block; height: 404px; margin: 0px auto; width: 500px;"></p> + +<p>Um dich noch mehr mit deiner Arbeit vertraut zu machen, <a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/assessment-finished/">schau dir die fertige Lösung an</a> (ohne im Quellcode zu spicken! )</p> + +<h2 id="Schritt-für-Schritt_Anleitung">Schritt-für-Schritt Anleitung</h2> + +<p>In den folgenden Abschnitten wird dir erklärt, was du tun musst.</p> + +<p>Grundaufbau:</p> + +<ol> + <li>Erzeuge eine Datei mit dem Namen <code>main.js</code>, und zwar im selben Verzeichnis, wie deine <code>index.html</code> Datei.</li> + <li>Verbinde deine externe JavaScript Datei <code>main.js </code>mit deiner HTML Datei, indem du es mithilfe des Script-tags {{htmlelement("script")}} in deinem HTML aufrufst. Füge die Zeile kurz vor dem schließenden <code></body></code> tag ein.</li> +</ol> + +<p> Vorgegebene Variablen und Functions:</p> + +<ol> + <li>Kopiere alle Code-Zeilen aus der Roh-Text-Datei, die unter der Überschrift "1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS" stehen und füge Sie an den Anfang deiner <code>main.js</code> Datei. Im Code wirst du 3 Variablen entdecken, die sich auf verschiedene Teile der Ausgabe beziehen: (<code>customName</code>) bezieht sich auf das "Enter custom name" Text Feld , the "Generate random story" button (<code>randomize</code>), and the {{htmlelement("p")}} element at the bottom of the HTML body that the story will be copied into (<code>story</code>), respectively. In addition you've got a function called <code>randomValueFromArray()</code> that takes an array, and returns one of the items stored inside the array at random.</li> + <li>Now look at the second section of the raw text file — "2. RAW TEXT STRINGS". This contains text strings that will act as input into our program. We'd like you to contain these inside variables inside <code>main.js</code>: + <ol> + <li>Store the first, big long, string of text inside a variable called <code>storyText</code>.</li> + <li>Store the first set of three strings inside an array called <code>insertX</code>.</li> + <li>Store the second set of three strings inside an array called <code>insertY</code>.</li> + <li>Store the third set of three strings inside an array called <code>insertZ</code>.</li> + </ol> + </li> +</ol> + +<p>Placing the event handler and incomplete function:</p> + +<ol> + <li>Now return to the raw text file.</li> + <li>Copy the code found underneath the heading "3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION" and paste it into the bottom of your <code>main.js</code> file. This: + <ul> + <li>Adds a click event listener to the <code>randomize</code> variable so that when the button it represents is clicked, the <code>result()</code> function is run.</li> + <li>Adds a partially-completed <code>result()</code> function definiton to your code. For the remainder of the assessment, you'll be filling in lines inside this function to complete it and make it work properly.</li> + </ul> + </li> +</ol> + +<p>Completing the <code>result()</code> function:</p> + +<ol> + <li>Create a new variable called <code>newStory</code>, and set it's value to equal <code>storyText</code>. This is needed so we can create a new random story each time the button is pressed and the function is run. If we made changes directly to <code>storyText</code>, we'd only be able to generate a new story once.</li> + <li>Create three new variables called <code>xItem</code>, <code>yItem</code>, and <code>zItem</code>, and make them equal to the result of calling <code>randomValueFromArray()</code> on your three arrays (the result in each case will be a random item out of each array it is called on). For example you can call the function and get it to return one random string out of <code>insertX</code> by writing <code>randomValueFromArray(insertX)</code>.</li> + <li>Next we want to replace the three placeholders in the <code>newStory</code> string — <code>:insertx:</code>, <code>:inserty:</code>, and <code>:insertz:</code> — with the strings stored in <code>xItem</code>, <code>yItem</code>, and <code>zItem</code>. There is a particular string method that will help you here — in each case, make the call to the method equal to <code>newStory</code>, so each time it is called, <code>newStory</code> is made equal to itself, but with substitutions made. So each time the button is pressed, these placeholders are each replaced with a random silly string. As a further hint, the method in question only replaces the first instance of the substring it finds, so you might need to make one of the calls twice.</li> + <li>Inside the first <code>if</code> block, add another string replacement method call to replace the name 'Bob' found in the <code>newStory</code> string with the <code>name</code> variable. In this block we are saying "If a value has been entered into the <code>customName</code> text input, replace Bob in the story with that custom name."</li> + <li>Inside the second <code>if</code> block, we are checking to see if the <code>uk</code> radio button has been selected. If so, we want to convert the weight and temperature values in the story from pounds and Fahrenheit into stones and centigrade. What you need to do is as follows: + <ol> + <li>Look up the formulae for converting pounds to stone, and Fahrenheit to centigrade.</li> + <li>Inside the line that defines the <code>weight</code> variable, replace 300 with a calculation that converts 300 pounds into stones. Concatenate <code>' stone'</code> onto the end of the result of the overall <code>Math.round()</code> call.</li> + <li>Inside the line that defines the <code>temperature</code> variable, replace 94 with a calculation that converts 94 Fahrenheit into centigrade. Concatenate <code>' centigrade'</code> onto the end of the result of the overall <code>Math.round()</code> call.</li> + <li>Just under the two variable definitions, add two more string replacement lines that replace '94 fahrenheit' with the contents of the <code>temperature</code> variable, and '300 pounds' with the contents of the <code>weight</code> variable.</li> + </ol> + </li> + <li>Finally, in the second-to-last line of the function, make the <code>textContent</code> property of the <code>story</code> variable (which references the paragraph) equal to <code>newStory</code>.</li> +</ol> + +<h2 id="Hints_and_tips">Hints and tips</h2> + +<ul> + <li>You don't need to edit the HTML in any way, except to apply the JavaScript to your HTML.</li> + <li>If you are unsure whether the JavaScript is applied to your HTML properly, try removing everything else from the JavaScript file temporarily, adding in a simple bit of JavaScript that you know will create an obvious effect, then saving and refreshing. The following for example turns the background of the {{htmlelement("html")}} element red — so the entire browser window should go red if the JavaScript is applied properly: + <pre class="brush: js">document.querySelector('html').style.backgroundColor = 'red';</pre> + </li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round">Math.round()</a></code> is a built-in JavaScript method that simply rounds the result of a calculation to the nearest whole number.</li> + <li>There are three instances of strings that need to be replaced. You may repeat the <code>replace()</code> method multiple times, or you can use regular expressions. For instance, <code>let text = 'I am the biggest lover, I love my love'; text.replace(/love/g,'like');</code> will replace all instances of 'love' to 'like'. Remember, Strings are immutable!</li> +</ul> + +<h2 id="Assessment">Assessment</h2> + +<p>If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the <a href="https://discourse.mozilla.org/t/silly-story-generator-assessment/24686">discussion thread for this exercise</a>, or in the <a href="irc://irc.mozilla.org/mdn">#mdn</a> IRC channel on <a href="https://wiki.mozilla.org/IRC">Mozilla IRC</a>. Try the exercise first — there is nothing to be gained by cheating!</p> + +<p>{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript">What is JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/A_first_splash">A first splash into JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables">Storing the information you need — Variables</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math">Basic math in JavaScript — numbers and operators</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Assessment: Silly story generator</a></li> +</ul> diff --git a/files/de/learn/javascript/first_steps/useful_string_methods/index.html b/files/de/learn/javascript/first_steps/useful_string_methods/index.html new file mode 100644 index 0000000000..e0df907ade --- /dev/null +++ b/files/de/learn/javascript/first_steps/useful_string_methods/index.html @@ -0,0 +1,656 @@ +--- +title: Useful string methods +slug: Learn/JavaScript/First_steps/Useful_string_methods +translation_of: Learn/JavaScript/First_steps/Useful_string_methods +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}</div> + +<p class="summary">Jetzt, da wir die Basics kennengelernt haben, gehen wir einen Schritt weiter und sehen uns hilfreiche Methoden an, die wir im Umgang mit Strings anwenden können. Dazu zählt zum Beispiel die Länge eines Textes, hinzufügen oder splitten von Strings, das Austauschen eines Buchstaben in einem Text-String und mehr...</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Voraussetzungen:</th> + <td>Grundlegende Computerkenntnisse, ein grundlegendes Verständnis von HTML und CSS, ein Verständnis dafür, was JavaScript ist.</td> + </tr> + <tr> + <th scope="row">Ziel:</th> + <td>Zu verstehen, dass Zeichenketten Objekte sind, und zu lernen, wie man einige der grundlegenden Methoden, die auf diesen Objekten verfügbar sind, verwendet, um Zeichenketten zu manipulieren.</td> + </tr> + </tbody> +</table> + +<h2 id="Zeichenketten_als_Objekte">Zeichenketten als Objekte</h2> + +<p id="Useful_string_methods">Die meisten Dinge in JavaScript sind Objekte. Wenn Sie einen String erstellen, zum Beispiel durch die Verwendung von</p> + +<pre class="brush: js">let string = 'This is my string';</pre> + +<p>wird Ihre Variable zu einer String-Objektinstanz und hat als Ergebnis eine große Anzahl von Eigenschaften und Methoden zur Verfügung. Sie können dies sehen, wenn Sie auf die {{jsxref("String")}} Objektseite gehen und die Liste auf der Seite nach unten scrollen!</p> + +<p><strong>Sooo, <u>bevor</u> Du jetzt Kopfschmerzen bekommst:</strong> Die meisten der Methoden must du jetzt am Anfang noch nicht wirklich kennen. Allerdings gibt es da ein paar, die Du am Anfang und später ziemlich oft nutzen wirst. Werfen wir also einen Blick darauf:</p> + +<p>Starten wir mit ein paar Beispielen in der <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">browser developer console</a>.</p> + +<h3 id="Länge_einer_Zeichenkette">Länge einer Zeichenkette</h3> + +<p>Das ist einfach. Nutze einfach {{jsxref("String.prototype.length", "length")}} . Probiere einfach mal folgenden Code:</p> + +<pre class="brush: js">let browserType = 'mozilla'; +browserType.length;</pre> + +<p>Das sollte Dir eine "7" zurückgeben, denn "mozilla" ist 7 Zeichen lang. Das kann man für verschiedene Dinge nutzen; Zum Beispiel: Du möchtest die Zeichenlänge einer Reihe von Namen herausfinden, um diese in der Reihenfolge ihrer Länge auszugeben. Oder lasse einen Nutzer wissen, das seine gerade getätigte Eingabe des Usernamens viel zu lang ist und nicht den Vorgaben entspricht.</p> + +<h3 id="Retrieving_a_specific_string_character">Retrieving a specific string character</h3> + +<p>On a related note, you can return any character inside a string by using <strong>square bracket notation</strong> — this means you include square brackets (<code>[]</code>) on the end of your variable name. Inside the square brackets you include the number of the character you want to return, so for example to retrieve the first letter you'd do this:</p> + +<pre class="brush: js">browserType[0];</pre> + +<p>Remember: computers count from 0, not 1! You could use this to, for example, find the first letter of a series of strings and order them alphabetically.</p> + +<p>To retrieve the last character of <em>any</em> string, we could use the following line, combining this technique with the <code>length</code> property we looked at above:</p> + +<pre class="brush: js">browserType[browserType.length-1];</pre> + +<p>The length of "mozilla" is 7, but because the count starts at 0, the character position is 6; using <code>length-1</code> gets us the last character.</p> + +<h3 id="Finding_a_substring_inside_a_string_and_extracting_it">Finding a substring inside a string and extracting it</h3> + +<ol> + <li>Sometimes you'll want to find if a smaller string is present inside a larger one (we generally say <em>if a substring is present inside a string</em>). This can be done using the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, which takes a single {{glossary("parameter")}} — the substring you want to search for. Try this: + + <pre class="brush: js">browserType.indexOf('zilla');</pre> + This gives us a result of 2, because the substring "zilla" starts at position 2 (0, 1, 2 — so 3 characters in) inside "mozilla". Such code could be used to filter strings. For example, we may have a list of web addresses and only want to print out the ones that contain "mozilla".</li> +</ol> + +<ol start="2"> + <li>This can be done in another way, which is possibly even more effective. Try the following: + <pre class="brush: js">browserType.indexOf('vanilla');</pre> + This should give you a result of <code>-1</code> — this is returned when the substring, in this case 'vanilla', is not found in the main string.<br> + <br> + You could use this to find all instances of strings that <strong>don't</strong> contain the substring 'mozilla', or <strong>do,</strong> if you use the negation operator, as shown below. You could do something like this: + + <pre class="brush: js">if(browserType.indexOf('mozilla') !== -1) { + // do stuff with the string +}</pre> + </li> + <li>When you know where a substring starts inside a string, and you know at which character you want it to end, {{jsxref("String.prototype.slice()", "slice()")}} can be used to extract it. Try the following: + <pre class="brush: js">browserType.slice(0,3);</pre> + This returns "moz" — the first parameter is the character position to start extracting at, and the second parameter is the character position after the last one to be extracted. So the slice happens from the first position, up to, but not including, the last position. In this example, since the starting index is 0, the second parameter is equal to the length of the string being returned.<br> + </li> + <li>Also, if you know that you want to extract all of the remaining characters in a string after a certain character, you don't have to include the second parameter! Instead, you only need to include the character position from where you want to extract the remaining characters in a string. Try the following: + <pre class="brush: js">browserType.slice(2);</pre> + This returns "zilla" — this is because the character position of 2 is the letter z, and because you didn't include a second parameter, the substring that was returned was all of the remaining characters in the string. </li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: The second parameter of <code>slice()</code> is optional: if you don't include it, the slice ends at the end of the original string. There are other options too; study the {{jsxref("String.prototype.slice()", "slice()")}} page to see what else you can find out.</p> +</div> + +<h3 id="Changing_case">Changing case</h3> + +<p>The string methods {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} and {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}} take a string and convert all the characters to lower- or uppercase, respectively. This can be useful for example if you want to normalize all user-entered data before storing it in a database.</p> + +<p>Let's try entering the following lines to see what happens:</p> + +<pre class="brush: js">let radData = 'My NaMe Is MuD'; +radData.toLowerCase(); +radData.toUpperCase();</pre> + +<h3 id="Updating_parts_of_a_string">Updating parts of a string</h3> + +<p>You can replace one substring inside a string with another substring using the {{jsxref("String.prototype.replace()", "replace()")}} method. This works very simply at a basic level, although there are some advanced things you can do with it that we won't go into yet.</p> + +<p>It takes two parameters — the string you want to replace, and the string you want to replace it with. Try this example:</p> + +<pre class="brush: js">browserType.replace('moz','van');</pre> + +<p>This returns "vanilla" in the console. But if you check the value of <code>browserType</code>, it is still "mozilla'. To actually update the value of the <code>browserType</code> variable in a real program, you'd have to set the variable value to be the result of the operation; it doesn't just update the substring value automatically. So you'd have to actually write this: <code>browserType = browserType.replace('moz','van');</code></p> + +<h2 id="Active_learning_examples">Active learning examples</h2> + +<p>In this section we'll get you to try your hand at writing some string manipulation code. In each exercise below, we have an array of strings, and a loop that processes each value in the array and displays it in a bulleted list. You don't need to understand arrays or loops right now — these will be explained in future articles. All you need to do in each case is write the code that will output the strings in the format that we want them in.</p> + +<p>Each example comes with a "Reset" button, which you can use to reset the code if you make a mistake and can't get it working again, and a "Show solution" button you can press to see a potential answer if you get really stuck.</p> + +<h3 id="Filtering_greeting_messages">Filtering greeting messages</h3> + +<p>In the first exercise we'll start you off simple — we have an array of greeting card messages, but we want to sort them to list just the Christmas messages. We want you to fill in a conditional test inside the <code>if( ... )</code> structure, to test each string and only print it in the list if it is a Christmas message.</p> + +<ol> + <li>First think about how you could test whether the message in each case is a Christmas message. What string is present in all of those messages, and what method could you use to test whether it is present?</li> + <li>You'll then need to write a conditional test of the form <em>operand1 operator operand2</em>. Is the thing on the left equal to the thing on the right? Or in this case, does the method call on the left return the result on the right?</li> + <li>Hint: In this case it is probably more useful to test whether the method call <em>isn't</em> equal to a certain result.</li> +</ol> + +<div class="hidden"> +<h6 id="Playable_code">Playable code</h6> + +<pre class="brush: html"><h2>Live output</h2> + +<div class="output" style="min-height: 125px;"> + +<ul> + +</ul> + +</div> + +<h2>Editable code</h2> +<p class="a11y-label">Press Esc to move focus away from the code area (Tab inserts a tab character).</p> + +<textarea id="code" class="playable-code" style="height: 290px; width: 95%"> +const list = document.querySelector('.output ul'); +list.innerHTML = ''; +let greetings = ['Happy Birthday!', + 'Merry Christmas my love', + 'A happy Christmas to all the family', + 'You\'re all I want for Christmas', + 'Get well soon']; + +for (let i = 0; i < greetings.length; i++) { + let input = greetings[i]; + // Your conditional test needs to go inside the parentheses + // in the line below, replacing what's currently there + if (greetings[i]) { + let listItem = document.createElement('li'); + listItem.textContent = input; + list.appendChild(listItem); + } +} +</textarea> + +<div class="playable-buttons"> + <input id="reset" type="button" value="Reset"> + <input id="solution" type="button" value="Show solution"> +</div> +</pre> + +<pre class="brush: css">html { + font-family: sans-serif; +} + +h2 { + font-size: 16px; +} + +.a11y-label { + margin: 0; + text-align: right; + font-size: 0.7rem; + width: 98%; +} + +body { + margin: 10px; + background: #f5f9fa; +}</pre> + +<pre class="brush: js">const textarea = document.getElementById('code'); +const reset = document.getElementById('reset'); +const solution = document.getElementById('solution'); +let code = textarea.value; +let userEntry = textarea.value; + +function updateCode() { + eval(textarea.value); +} + +reset.addEventListener('click', function() { + textarea.value = code; + userEntry = textarea.value; + solutionEntry = jsSolution; + solution.value = 'Show solution'; + updateCode(); +}); + +solution.addEventListener('click', function() { + if(solution.value === 'Show solution') { + textarea.value = solutionEntry; + solution.value = 'Hide solution'; + } else { + textarea.value = userEntry; + solution.value = 'Show solution'; + } + updateCode(); +}); + +const jsSolution = 'const list = document.querySelector(\'.output ul\');' + +'\nlist.innerHTML = \'\';' + +'\nlet greetings = [\'Happy Birthday!\',' + +'\n \'Merry Christmas my love\',' + +'\n \'A happy Christmas to all the family\',' + +'\n \'You\\\'re all I want for Christmas\',' + +'\n \'Get well soon\'];' + +'\n' + +'\nfor (let i = 0; i < greetings.length; i++) {' + +'\n let input = greetings[i];' + +'\n if (greetings[i].indexOf(\'Christmas\') !== -1) {' + +'\n let result = input;' + +'\n let listItem = document.createElement(\'li\');' + +'\n listItem.textContent = result;' + +'\n list.appendChild(listItem);' + +'\n }' + +'\n}'; + +let solutionEntry = jsSolution; + +textarea.addEventListener('input', updateCode); +window.addEventListener('load', updateCode); + +// stop tab key tabbing out of textarea and +// make it write a tab at the caret position instead + +textarea.onkeydown = function(e){ + if (e.keyCode === 9) { + e.preventDefault(); + insertAtCaret('\t'); + } + + if (e.keyCode === 27) { + textarea.blur(); + } +}; + +function insertAtCaret(text) { + const scrollPos = textarea.scrollTop; + const caretPos = textarea.selectionStart; + const front = (textarea.value).substring(0, caretPos); + const back = (textarea.value).substring(textarea.selectionEnd, textarea.value.length); + + textarea.value = front + text + back; + caretPos = caretPos + text.length; + textarea.selectionStart = caretPos; + textarea.selectionEnd = caretPos; + textarea.focus(); + textarea.scrollTop = scrollPos; +} + +// Update the saved userCode every time the user updates the text area code + +textarea.onkeyup = function(){ + // We only want to save the state when the user code is being shown, + // not the solution, so that solution is not saved over the user code + if(solution.value === 'Show solution') { + userEntry = textarea.value; + } else { + solutionEntry = textarea.value; + } + + updateCode(); +};</pre> +</div> + +<p>{{ EmbedLiveSample('Playable_code', '100%', 590, "", "", "hide-codepen-jsfiddle") }}</p> + +<h3 id="Fixing_capitalization">Fixing capitalization</h3> + +<p>In this exercise we have the names of cities in the United Kingdom, but the capitalization is all messed up. We want you to change them so that they are all lower case, except for a capital first letter. A good way to do this is to:</p> + +<ol> + <li>Convert the whole of the string contained in the <code>input</code> variable to lower case and store it in a new variable.</li> + <li>Grab the first letter of the string in this new variable and store it in another variable.</li> + <li>Using this latest variable as a substring, replace the first letter of the lowercase string with the first letter of the lowercase string changed to upper case. Store the result of this replace procedure in another new variable.</li> + <li>Change the value of the <code>result</code> variable to equal to the final result, not the <code>input</code>.</li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: A hint — the parameters of the string methods don't have to be string literals; they can also be variables, or even variables with a method being invoked on them.</p> +</div> + +<div class="hidden"> +<h6 id="Playable_code_2">Playable code 2</h6> + +<pre class="brush: html"><h2>Live output</h2> + +<div class="output" style="min-height: 125px;"> + +<ul> + +</ul> + +</div> + +<h2>Editable code</h2> +<p class="a11y-label">Press Esc to move focus away from the code area (Tab inserts a tab character).</p> + +<textarea id="code" class="playable-code" style="height: 250px; width: 95%"> +const list = document.querySelector('.output ul'); +list.innerHTML = ''; +let cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOL']; + +for (let i = 0; i < cities.length; i++) { + let input = cities[i]; + // write your code just below here + + let result = input; + let listItem = document.createElement('li'); + listItem.textContent = result; + list.appendChild(listItem); +} +</textarea> + +<div class="playable-buttons"> + <input id="reset" type="button" value="Reset"> + <input id="solution" type="button" value="Show solution"> +</div> +</pre> + +<pre class="brush: css">html { + font-family: sans-serif; +} + +h2 { + font-size: 16px; +} + +.a11y-label { + margin: 0; + text-align: right; + font-size: 0.7rem; + width: 98%; +} + +body { + margin: 10px; + background: #f5f9fa; +}</pre> + +<pre class="brush: js">const textarea = document.getElementById('code'); +const reset = document.getElementById('reset'); +const solution = document.getElementById('solution'); +let code = textarea.value; +let userEntry = textarea.value; + +function updateCode() { + eval(textarea.value); +} + +reset.addEventListener('click', function() { + textarea.value = code; + userEntry = textarea.value; + solutionEntry = jsSolution; + solution.value = 'Show solution'; + updateCode(); +}); + +solution.addEventListener('click', function() { + if(solution.value === 'Show solution') { + textarea.value = solutionEntry; + solution.value = 'Hide solution'; + } else { + textarea.value = userEntry; + solution.value = 'Show solution'; + } + updateCode(); +}); + +const jsSolution = 'const list = document.querySelector(\'.output ul\');' + +'\nlist.innerHTML = \'\';' + +'\nlet cities = [\'lonDon\', \'ManCHESTer\', \'BiRmiNGHAM\', \'liVERpoOL\'];' + +'\n' + +'\nfor (let i = 0; i < cities.length; i++) {' + +'\n let input = cities[i];' + +'\n let lower = input.toLowerCase();' + +'\n let firstLetter = lower.slice(0,1);' + +'\n let capitalized = lower.replace(firstLetter,firstLetter.toUpperCase());' + +'\n let result = capitalized;' + +'\n let listItem = document.createElement(\'li\');' + +'\n listItem.textContent = result;' + +'\n list.appendChild(listItem);' + +'\n' + +'\n}'; + +let solutionEntry = jsSolution; + +textarea.addEventListener('input', updateCode); +window.addEventListener('load', updateCode); + +// stop tab key tabbing out of textarea and +// make it write a tab at the caret position instead + +textarea.onkeydown = function(e){ + if (e.keyCode === 9) { + e.preventDefault(); + insertAtCaret('\t'); + } + + if (e.keyCode === 27) { + textarea.blur(); + } +}; + +function insertAtCaret(text) { + const scrollPos = textarea.scrollTop; + const caretPos = textarea.selectionStart; + const front = (textarea.value).substring(0, caretPos); + const back = (textarea.value).substring(textarea.selectionEnd, textarea.value.length); + + textarea.value = front + text + back; + caretPos = caretPos + text.length; + textarea.selectionStart = caretPos; + textarea.selectionEnd = caretPos; + textarea.focus(); + textarea.scrollTop = scrollPos; +} + +// Update the saved userCode every time the user updates the text area code + +textarea.onkeyup = function(){ + // We only want to save the state when the user code is being shown, + // not the solution, so that solution is not saved over the user code + if(solution.value === 'Show solution') { + userEntry = textarea.value; + } else { + solutionEntry = textarea.value; + } + + updateCode(); +};</pre> +</div> + +<p>{{ EmbedLiveSample('Playable_code_2', '100%', 550, "", "", "hide-codepen-jsfiddle") }}</p> + +<h3 id="Making_new_strings_from_old_parts">Making new strings from old parts</h3> + +<p>In this last exercise, the array contains a bunch of strings containing information about train stations in the North of England. The strings are data items that contain the three-letter station code, followed by some machine-readable data, followed by a semicolon, followed by the human-readable station name. For example:</p> + +<pre>MAN675847583748sjt567654;Manchester Piccadilly</pre> + +<p>We want to extract the station code and name, and put them together in a string with the following structure:</p> + +<pre>MAN: Manchester Piccadilly</pre> + +<p>We'd recommend doing it like this:</p> + +<ol> + <li>Extract the three-letter station code and store it in a new variable.</li> + <li>Find the character index number of the semicolon.</li> + <li>Extract the human-readable station name using the semicolon character index number as a reference point, and store it in a new variable.</li> + <li>Concatenate the two new variables and a string literal to make the final string.</li> + <li>Change the value of the <code>result</code> variable to equal to the final string, not the <code>input</code>.</li> +</ol> + +<div class="hidden"> +<h6 id="Playable_code_3">Playable code 3</h6> + +<pre class="brush: html"><h2>Live output</h2> + +<div class="output" style="min-height: 125px;"> + +<ul> + +</ul> + +</div> + +<h2>Editable code</h2> +<p class="a11y-label">Press Esc to move focus away from the code area (Tab inserts a tab character).</p> + +<textarea id="code" class="playable-code" style="height: 285px; width: 95%"> +const list = document.querySelector('.output ul'); +list.innerHTML = ''; +let stations = ['MAN675847583748sjt567654;Manchester Piccadilly', + 'GNF576746573fhdg4737dh4;Greenfield', + 'LIV5hg65hd737456236dch46dg4;Liverpool Lime Street', + 'SYB4f65hf75f736463;Stalybridge', + 'HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield']; + +for (let i = 0; i < stations.length; i++) { + let input = stations[i]; + // write your code just below here + + let result = input; + let listItem = document.createElement('li'); + listItem.textContent = result; + list.appendChild(listItem); +} +</textarea> + +<div class="playable-buttons"> + <input id="reset" type="button" value="Reset"> + <input id="solution" type="button" value="Show solution"> +</div> +</pre> + +<pre class="brush: css">html { + font-family: sans-serif; +} + +h2 { + font-size: 16px; +} + +.a11y-label { + margin: 0; + text-align: right; + font-size: 0.7rem; + width: 98%; +} + +body { + margin: 10px; + background: #f5f9fa; +} +</pre> + +<pre class="brush: js">const textarea = document.getElementById('code'); +const reset = document.getElementById('reset'); +const solution = document.getElementById('solution'); +let code = textarea.value; +let userEntry = textarea.value; + +function updateCode() { + eval(textarea.value); +} + +reset.addEventListener('click', function() { + textarea.value = code; + userEntry = textarea.value; + solutionEntry = jsSolution; + solution.value = 'Show solution'; + updateCode(); +}); + +solution.addEventListener('click', function() { + if(solution.value === 'Show solution') { + textarea.value = solutionEntry; + solution.value = 'Hide solution'; + } else { + textarea.value = userEntry; + solution.value = 'Show solution'; + } + updateCode(); +}); + +const jsSolution = 'const list = document.querySelector(\'.output ul\');' + +'\nlist.innerHTML = \'\';' + +'\nlet stations = [\'MAN675847583748sjt567654;Manchester Piccadilly\',' + +'\n \'GNF576746573fhdg4737dh4;Greenfield\',' + +'\n \'LIV5hg65hd737456236dch46dg4;Liverpool Lime Street\',' + +'\n \'SYB4f65hf75f736463;Stalybridge\',' + +'\n \'HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield\'];' + +'\n' + +'\nfor (let i = 0; i < stations.length; i++) {' + +'\n let input = stations[i];' + +'\n let code = input.slice(0,3);' + +'\n let semiC = input.indexOf(\';\');' + +'\n let name = input.slice(semiC + 1);' + +'\n let result = code + \': \' + name;' + +'\n let listItem = document.createElement(\'li\');' + +'\n listItem.textContent = result;' + +'\n list.appendChild(listItem);' + +'\n}'; + +let solutionEntry = jsSolution; + +textarea.addEventListener('input', updateCode); +window.addEventListener('load', updateCode); + +// stop tab key tabbing out of textarea and +// make it write a tab at the caret position instead + +textarea.onkeydown = function(e){ + if (e.keyCode === 9) { + e.preventDefault(); + insertAtCaret('\t'); + } + + if (e.keyCode === 27) { + textarea.blur(); + } +}; + +function insertAtCaret(text) { + const scrollPos = textarea.scrollTop; + const caretPos = textarea.selectionStart; + const front = (textarea.value).substring(0, caretPos); + const back = (textarea.value).substring(textarea.selectionEnd, textarea.value.length); + + textarea.value = front + text + back; + caretPos = caretPos + text.length; + textarea.selectionStart = caretPos; + textarea.selectionEnd = caretPos; + textarea.focus(); + textarea.scrollTop = scrollPos; +} + +// Update the saved userCode every time the user updates the text area code + +textarea.onkeyup = function(){ + // We only want to save the state when the user code is being shown, + // not the solution, so that solution is not saved over the user code + if(solution.value === 'Show solution') { + userEntry = textarea.value; + } else { + solutionEntry = textarea.value; + } + + updateCode(); +};</pre> +</div> + +<p>{{ EmbedLiveSample('Playable_code_3', '100%', 585, "", "", "hide-codepen-jsfiddle") }}</p> + +<h2 id="Conclusion">Conclusion</h2> + +<p>You can't escape the fact that being able to handle words and sentences in programming is very important — particularly in JavaScript, as websites are all about communicating with people. This article has given you the basics that you need to know about manipulating strings for now. This should serve you well as you go into more complex topics in the future. Next, we're going to look at the last major type of data we need to focus on in the short term — arrays.</p> + +<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript">What is JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/A_first_splash">A first splash into JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables">Storing the information you need — Variables</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math">Basic math in JavaScript — numbers and operators</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Assessment: Silly story generator</a></li> +</ul> diff --git a/files/de/learn/javascript/first_steps/variables/index.html b/files/de/learn/javascript/first_steps/variables/index.html new file mode 100644 index 0000000000..d8906f7d02 --- /dev/null +++ b/files/de/learn/javascript/first_steps/variables/index.html @@ -0,0 +1,386 @@ +--- +title: Speichern der benötigten Informationen — Variablen +slug: Learn/JavaScript/First_steps/Variables +translation_of: Learn/JavaScript/First_steps/Variables +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps")}}</div> + +<p class="summary">After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article, we will get down to the real basics, looking at how to work with the most basic building blocks of JavaScript — Variables.</p> + +<table class="learn-box"> + <tbody> + <tr> + <th scope="row">Prerequisites:</th> + <td>Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.</td> + </tr> + <tr> + <th scope="row">Objective:</th> + <td>To gain familiarity with the basics of JavaScript variables.</td> + </tr> + </tbody> +</table> + +<h2 id="Tools_you_need">Tools you need</h2> + +<p>Throughout this article, you'll be asked to type in lines of code to test your understanding of the content. If you are using a desktop browser, the best place to type your sample code is your browser's JavaScript console (see <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">What are browser developer tools</a> for more information on how to access this tool).</p> + +<p>However, we have also provided a simple JavaScript console embedded in the page below for you to enter this code into, in case you are not using a browser with a JavaScript console easily available, or find an in-page console more comfortable.</p> + +<h2 id="Was_ist_eine_Variable">Was ist eine Variable?</h2> + +<p>Eine Variable ist ein Behälter für einen Wert, wie z.B. eine Zahl, welche wir vielleicht für eine Summe benötigen, oder eine Zeichenkette die wir für einen Teil eines Satzes brauchen. Eine Besonderheit von Variablen ist, dass ihr Wert verändert werden kann. Hier ein Beispiel:</p> + +<pre class="brush: html"><button>Press me</button></pre> + +<pre class="brush: js">var button = document.querySelector('button'); + +button.onclick = function() { + var name = prompt('Wie heißt du?'); + alert('Hallo ' + name + ', schön dich zu sehen!'); +}</pre> + +<p>{{ EmbedLiveSample('What_is_a_variable', '100%', 50, "", "", "hide-codepen-jsfiddle") }}</p> + +<p>In diesem Beispiel werden beim Drücken des Buttons einige Zeilen Code ausgeführt. Die erste Zeile zeigt eine Box an, welche den Leser nach seinem Namen fragt und den Wert anschließend in einer Variable abspeichert. Die zweite Zeile zeigt eine Willkommensnachricht, die den Namen enthält, welcher dem Wert der Variable entnommen wird.</p> + +<p>Um zu verstehen, warum das so nützlich ist, überlegen wir mal, wie wir das Beispiel ohne eine Variable schreiben würden. Es würde etwa so aussehen:</p> + +<pre class="example-bad">var name = prompt('Wie heißt du?'); + +if (name === 'Adam') { + alert('Hallo Adam, schön dich zu sehen!'); +} else if (name === 'Alan') { + alert('Hallo Alan, schön dich zu sehen!'); +} else if (name === 'Bella') { + alert('Hallo Bella, schön dich zu sehen!'); +} else if (name === 'Bianca') { + alert('Hallo Bianca, schön dich zu sehen!'); +} else if (name === 'Chris') { + alert('Hallo Chris, schön dich zu sehen!'); +} + +// ... und so weiter ...</pre> + +<p>You may not fully understand the syntax we are using (yet!), but you should be able to get the idea — if we didn't have variables available, we'd have to implement a giant code block that checked what the entered name was, and then display the appropriate message for that name. This is obviously really inefficient (the code is a lot bigger, even for only five choices), and it just wouldn't work — you couldn't possibly store all possible choices.</p> + +<p>Variables just make sense, and as you learn more about JavaScript they will start to become second nature.</p> + +<p>Another special thing about variables is that they can contain just about anything — not just strings and numbers. Variables can also contain complex data and even entire functions to do amazing things. You'll learn more about this as you go along.</p> + +<p><u><strong>Note that we say variables contain values. This is an important distinction to make. Variables aren't the values themselves; they are containers for values. You can think of them being like little cardboard boxes that you can store things in.</strong></u></p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13506/boxes.png" style="display: block; height: 436px; margin: 0px auto; width: 1052px;"></p> + +<h2 id="Eine_Variable_deklarieren">Eine Variable deklarieren</h2> + +<p>To use a variable you've first got to create it — more accurately, we call this declaring the variable. To do this, we type the keyword var followed by the name you want to call your variable:</p> + +<pre class="brush: js">var myName; +var myAge;</pre> + +<p>Here we're creating two variables called <code>myName</code> and <code>myAge</code>. Try typing these lines in now in your web browser's console, or in the below console (You can <a href="https://mdn.github.io/learning-area/javascript/introduction-to-js-1/variables/index.html">open this console</a> in a separate tab or window if you'd prefer that). After that, try creating a variable (or two) with your own name choices.</p> + +<div class="hidden"> +<h6 id="Hidden_code">Hidden code</h6> + +<pre class="brush: html"><!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <title>JavaScript console</title> + <style> + * { + box-sizing: border-box; + } + + html { + background-color: #0C323D; + color: #809089; + font-family: monospace; + } + + body { + max-width: 700px; + } + + p { + margin: 0; + width: 1%; + padding: 0 1%; + font-size: 16px; + line-height: 1.5; + float: left; + } + + .input p { + margin-right: 1%; + } + + .output p { + width: 100%; + } + + .input input { + width: 96%; + float: left; + border: none; + font-size: 16px; + line-height: 1.5; + font-family: monospace; + padding: 0; + background: #0C323D; + color: #809089; + } + + div { + clear: both; + } + + </style> + </head> + <body> + + + </body> + + <script> + var geval = eval; + function createInput() { + var inputDiv = document.createElement('div'); + var inputPara = document.createElement('p'); + var inputForm = document.createElement('input'); + + inputDiv.setAttribute('class','input'); + inputPara.textContent = '>'; + inputDiv.appendChild(inputPara); + inputDiv.appendChild(inputForm); + document.body.appendChild(inputDiv); + + if(document.querySelectorAll('div').length > 1) { + inputForm.focus(); + } + + inputForm.addEventListener('change', executeCode); + } + + function executeCode(e) { + try { + var result = geval(e.target.value); + } catch(e) { + var result = 'error — ' + e.message; + } + + var outputDiv = document.createElement('div'); + var outputPara = document.createElement('p'); + + outputDiv.setAttribute('class','output'); + outputPara.textContent = 'Result: ' + result; + outputDiv.appendChild(outputPara); + document.body.appendChild(outputDiv); + + e.target.disabled = true; + e.target.parentNode.style.opacity = '0.5'; + + createInput() + } + + createInput(); + + </script> +</html></pre> +</div> + +<p>{{ EmbedLiveSample('Hidden_code', '100%', 300, "", "", "hide-codepen-jsfiddle") }}</p> + +<div class="note"> +<p><strong>Note</strong>: In JavaScript, all code instructions should end with a semi-colon (<code>;</code>) — your code may work correctly for single lines, but probably won't when you are writing multiple lines of code together. Try to get into the habit of including it.</p> +</div> + +<p>You can test whether these values now exist in the execution environment by typing just the variable's name, e.g.</p> + +<pre class="brush: js">myName; +myAge;</pre> + +<p>They currently have no value; they are empty containers. When you enter the variable names, you should get a value of <code>undefined</code> returned. If they don't exist, you'll get an error message — try typing in</p> + +<pre class="brush: js">scoobyDoo;</pre> + +<div class="note"> +<p><strong>Note</strong>: Don't confuse a variable that exists but has no value defined with a variable that doesn't exist at all — they are very different things. In the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. No value defined would mean that there IS a box, but it has no value inside it.</p> +</div> + +<h2 id="Eine_Variable_initialisieren">Eine Variable initialisieren</h2> + +<p>Once you've declared a variable, you can initialize it with a value. You do this by typing the variable name, followed by an equals sign (<code>=</code>), followed by the value you want to give it. For example:</p> + +<pre class="brush: js">myName = 'Chris'; +myAge = 37;</pre> + +<p>Try going back to the console now and typing in these lines. You should see the value you've assigned to the variable returned in the console to confirm it, in each case. Again, you can return your variable values by simply typing their name into the console — try these again:</p> + +<pre class="brush: js">myName; +myAge;</pre> + +<p>You can declare and initialize a variable at the same time, like this:</p> + +<pre class="brush: js">var myName = 'Chris';</pre> + +<p>This is probably what you'll do most of the time, as it is quicker than doing the two actions on two separate lines.</p> + +<div class="note"> +<p><strong>Note</strong>: If you write a multiline JavaScript program that declares and initializes a variable, you can actually declare it after you initialize it and it will still work. This is because variable declarations are generally done first before the rest of the code is executed. This is called <strong>hoisting</strong> — read <a href="/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting">var hoisting</a> for more detail on the subject.</p> +</div> + +<h2 id="Eine_Variable_aktualisieren">Eine Variable aktualisieren</h2> + +<p>Once a variable has been initialized with a value, you can change (or update) that value by simply giving it a different value. Try entering the following lines into your console:</p> + +<pre class="brush: js">myName = 'Bob'; +myAge = 40;</pre> + +<h3 id="An_aside_on_variable_naming_rules">An aside on variable naming rules</h3> + +<p>You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.</p> + +<ul> + <li>You shouldn't use other characters because they may cause errors or be hard to understand for an international audience.</li> + <li>Don't use underscores at the start of variable names — this is used in certain JavaScript constructs to mean specific things, so may get confusing.</li> + <li>Don't use numbers at the start of variables. This isn't allowed and will cause an error.</li> + <li>A safe convention to stick to is so-called <a href="https://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms">"lower camel case"</a>, where you stick together multiple words, using lower case for the whole first word and then capitalize subsequent words. We've been using this for our variable names in the article so far.</li> + <li>Make variable names intuitive, so they describe the data they contain. Don't just use single letters/numbers, or big long phrases.</li> + <li>Variables are case sensitive — so <code>myage</code> is a different variable to <code>myAge</code>.</li> + <li>One last point — you also need to avoid using JavaScript reserved words as your variable names — by this, we mean the words that make up the actual syntax of JavaScript! So you can't use words like <code>var</code>, <code>function</code>, <code>let</code>, and <code>for</code> as variable names. Browsers will recognize them as different code items, and so you'll get errors.</li> +</ul> + +<div class="note"> +<p><strong>Note</strong>: You can find a fairly complete list of reserved keywords to avoid at <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords">Lexical grammar — keywords</a>.</p> +</div> + +<p>Good name examples:</p> + +<pre class="example-good">age +myAge +init +initialColor +finalOutputValue +audio1 +audio2</pre> + +<p>Bad name examples:</p> + +<pre class="example-bad">1 +a +_12 +myage +MYAGE +var +Document +skjfndskjfnbdskjfb +thisisareallylongstupidvariablenameman</pre> + +<p>Error-prone name examples:</p> + +<pre class="example-invalid">var +Document +</pre> + +<p>Try creating a few more variables now, with the above guidance in mind.</p> + +<h2 id="Typen_von_Variablen">Typen von Variablen</h2> + +<p>There are a few different types of data we can store in variables. In this section we'll describe these in brief, then in future articles, you'll learn about them in more detail.</p> + +<p>So far we've looked at the first two, but there are others.</p> + +<h3 id="Numbers">Numbers</h3> + +<p>You can store numbers in variables, either whole numbers like 30 (also called integers) or decimal numbers like 2.456 (also called floats or floating point numbers). You don't need to declare variable types in JavaScript, unlike some other programming languages. When you give a variable a number value, you don't include quotes:</p> + +<pre class="brush: js">var myAge = 17;</pre> + +<h3 id="Strings">Strings</h3> + +<p>Strings are pieces of text. When you give a variable a string value, you need to wrap it in single or double quote marks, otherwise, JavaScript will try to interpret it as another variable name.</p> + +<pre class="brush: js">var dolphinGoodbye = 'So long and thanks for all the fish';</pre> + +<h3 id="Booleans">Booleans</h3> + +<p>Booleans are true/false values — they can have two values, <code>true</code> or <code>false</code>. These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be:</p> + +<pre class="brush: js">var iAmAlive = true;</pre> + +<p>Whereas in reality it would be used more like this:</p> + +<pre class="brush: js">var test = 6 < 3;</pre> + +<p>This is using the "less than" operator (<code><</code>) to test whether 6 is less than 3. As you might expect, it will return <code>false</code>, because 6 is not less than 3! You will learn a lot more about such operators later on in the course.</p> + +<h3 id="Arrays">Arrays</h3> + +<p>An array is a single object that contains multiple values enclosed in square brackets and separated by commas. Try entering the following lines into your console:</p> + +<pre class="brush: js">var myNameArray = ['Chris', 'Bob', 'Jim']; +var myNumberArray = [10,15,40];</pre> + +<p>Once these arrays are defined, you can access each value by their location within the array. Try these lines:</p> + +<pre class="brush: js">myNameArray[0]; // should return 'Chris' +myNumberArray[2]; // should return 40</pre> + +<p>The square brackets specify an index value corresponding to the position of the value you want returned. You might have noticed that arrays in JavaScript are zero-indexed: the first element is at index 0.</p> + +<p>You'll learn a lot more about arrays in a future article.</p> + +<h3 id="Objects">Objects</h3> + +<p>In programming, an object is a structure of the code that models a real-life object. You can have a simple object that represents a car park and contains information about its width and length, or you could have an object that represents a person, and contains data about their name, height, weight, what language they speak, how to say hello to them, and more.</p> + +<p>Try entering the following line into your console:</p> + +<pre class="brush: js">var dog = { name : 'Spot', breed : 'Dalmatian' };</pre> + +<p>To retrieve the information stored in the object, you can use the following syntax:</p> + +<pre class="brush: js">dog.name</pre> + +<p>We won't be looking at objects any more for now — you can learn more about those in a future module.</p> + +<h2 id="Dynamic_typing">Dynamic typing</h2> + +<p>JavaScript is a "dynamically typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (e.g. numbers, strings, arrays, etc).</p> + +<p>For example, if you declare a variable and give it a value encapsulated in quotes, the browser will treat the variable as a string:</p> + +<pre class="brush: js">var myString = 'Hello';</pre> + +<p>It will still be a string, even if it contains numbers, so be careful:</p> + +<pre class="brush: js">var myNumber = '500'; // oops, this is still a string +typeof myNumber; +myNumber = 500; // much better — now this is a number +typeof myNumber;</pre> + +<p>Try entering the four lines above into your console one by one, and see what the results are. You'll notice that we are using a special operator called <code>typeof</code> — this returns the data type of the variable you pass into it. The first time it is called, it should return <code>string</code>, as at that point the <code>myNumber</code> variable contains a string, <code>'500'</code>. Have a look and see what it returns the second time you call it.</p> + +<h2 id="Zusammenfassung">Zusammenfassung</h2> + +<p>By now you should know a reasonable amount about JavaScript variables and how to create them. In the next article, we'll focus on numbers in more detail, looking at how to do basic math in JavaScript.</p> + +<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Maths", "Learn/JavaScript/First_steps")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript">What is JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/A_first_splash">The first splash into JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables">Storing the information you need — Variables</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math">Basic math in JavaScript — numbers and operators</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Assessment: Silly story generator</a></li> +</ul> diff --git a/files/de/learn/javascript/first_steps/was_ist_javascript/index.html b/files/de/learn/javascript/first_steps/was_ist_javascript/index.html new file mode 100644 index 0000000000..247b4744c5 --- /dev/null +++ b/files/de/learn/javascript/first_steps/was_ist_javascript/index.html @@ -0,0 +1,339 @@ +--- +title: Was ist JavaScript? +slug: Learn/JavaScript/First_steps/Was_ist_JavaScript +translation_of: Learn/JavaScript/First_steps/What_is_JavaScript +--- +<div>{{LearnSidebar}}</div> + +<div>{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}</div> + +<p class="summary">Willkommen zum MDN-Einsteigerkurs für JavaScript! Im ersten Artikel werden wir uns JavaScript von aussen anschauen und Fragen beantworten wie "Was ist das?" oder "Was macht das?", und wir stellen sicher, das du weißt was JavaScript ist.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Voraussetzungen:</th> + <td>Umgang mit einem Computer und ein Grundverständniss von HTML und CSS</td> + </tr> + <tr> + <th scope="row">Thema:</th> + <td>JavaScript kennenlernen, was JavaScript tun kann und wie es in einer Webseite arbeitet.</td> + </tr> + </tbody> +</table> + +<h2 id="Eine_Experten_Definition">Eine Experten Definition</h2> + +<p>JavaScript ist eine Programmiersprache mit der sich komplexe Programme in eine Webseite realisieren lassen. Immer wenn eine Webseite mehr macht als nur statische Informationen anzuzeigen, (zum Beispiel:</p> + +<ul> + <li>Zeitliche Inhalt-Updates ( Liveticker )</li> + <li>interaktive Karten ( Google Maps)</li> + <li>animierte 2D/3D Grafiken ( Spiele )</li> + <li>...)</li> +</ul> + +<p>kannst du dir sicher sein das JavaScript benutzt wurde. Es ist die Dritte der Drei Standard-Technologien im Web, die anderen beiden ( <a href="de/Learn/HTML">HTML </a>und <a href="/de/docs/Learn/CSS">CSS </a>) werden in anderen Bereichen des MDN eingeführt und referenziert.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13502/cake.png" style="display: block; margin: 0 auto;"></p> + +<ul> + <li>{{glossary("HTML")}} ist die Markup-Language, die wir benutzen, um eine Webseite zu strukturieren und unsere Inhalte darzustellen, zum Beispiel durch Paragraphen, Überschriften, Tabellen aber auch um Bilder und Videos in die Webseite einzubinden.</li> + <li>{{glossary("CSS")}} ist die Sprache, um Stil-Regeln für HTML zu definieren, zum Beispiel, indem wir die Hintergrundfarbe und die Schriftart ändern.</li> + <li>{{glossary("JavaScript")}} ist eine Progammiersprache, die es erlaubt dynamische Updates der Inhalte, animierte Bilder und noch sehr viel mehr zu realisieren.</li> +</ul> + +<p>Die drei Teile bauen gut auf einander auf. Hier mal ein einfaches Beispiel: Wir können zunächst HTML benutzten, um eine Struktur zu bauen.</p> + +<pre class="brush: html notranslate"><p>Player 1: Chris</p></pre> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13422/just-html.png" style="height: 28px; width: 108px;"></p> + +<p>Anschließend können wir mit einigen CSS-Regeln denn Satz schön aussehen lassen:</p> + +<pre class="brush: css notranslate">p { + font-family: 'helvetica neue', helvetica, sans-serif; + letter-spacing: 1px; + text-transform: uppercase; + text-align: center; + border: 2px solid rgba(0,0,200,0.6); + background: rgba(0,0,200,0.3); + color: rgba(0,0,200,0.6); + box-shadow: 1px 1px 2px rgba(0,0,200,0.4); + border-radius: 10px; + padding: 3px 10px; + display: inline-block; + cursor:pointer; +}</pre> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13424/html-and-css.png" style="height: 48px; width: 187px;"></p> + +<p>Und zum Schluss können wir mit etwas JavaScript eine Reaktion auf das Klicken des Benutzers implementieren:</p> + +<pre class="brush: js notranslate">var para = document.querySelector('p'); + +para.addEventListener('click', updateName); + +function updateName() { + var name = prompt('Enter a new name'); + para.textContent = 'Player 1: ' + name; +} +</pre> + +<p>{{ EmbedLiveSample('A_high-level_definition', '100%', 80) }}</p> + +<p>Klick auf das Label und sieh, was passiert (den <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/what-is-js/javascript-label.html">Code</a> findest du auf GitHub und hier kannst du es in <a href="https://mdn.github.io/learning-area/javascript/introduction-to-js-1/what-is-js/javascript-label.html">Aktion </a>sehen).</p> + +<h2 id="So_und_was_kann_ich_jetzt_damit_machen">So und was kann ich jetzt damit machen?</h2> + +<p>Der Kern von JavaScript ähnelt dem anderer Programmiersprachen. In JavaScript kannst du:</p> + +<ul> + <li>Nützliche Werte in Variablen speichern. Wie im Beispiel als wir eine Variable verwendet haben um den von dir eingebenen Namen zu speichern.</li> + <li>Operationen auf Texten ( in der Programmierung "Strings" genannt). Im oberen Beispiel hatten wir den String "Player 1:" und die Variable <code>name</code> verbunden und (wenn <code>name</code> "Chris" ist) haben wir den Text "Player 1: Chris" bekommen.</li> + <li>Mit Code auf Events in einer Webseite reagieren. Wir haben ein {{Event("click")}} Event benutzt um darauf zu reagieren wenn man auf das Label drückt.</li> + <li>Und viel mehr. ( siehe jedes größere Webprojekt.)</li> +</ul> + +<p>Aber es gibt noch andere Funktionen die auf dem Kern von JavaScript aufbauen. Die sogenannten <strong>Application Programming Interfaces (APIs) </strong>geben dir noch mehr Funktionen mit denen du deine Projekte aufbessern kann.</p> + +<p>APIs sind von anderen Programmieren geschriebener Code die dir mehr Möglichkeiten geben für dein Programm. Die für dich schwer oder unmöglich wären selber zu programmieren. Sie sind das gleiche was Werkzeuge und Material für Handwerker sind. Es wäre deutlich schwerer alleine erst alle Werkzeuge und dann alle Materiallien herzustellen.</p> + +<p>Die APIs kann man generell in zwei Kategorien einteilen:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13508/browser.png" style="display: block; height: 511px; margin: 0px auto; width: 815px;"></p> + +<p><strong>Browser APIs </strong>sind vom Webbrowser des Benutzers. Und sie können auf Ressourcen des computers zugreifen, oder erledigen Dinge die sehr komlpex sind. Ein paar Beispiele:</p> + +<ul> + <li>Die {{domxref("Document_Object_Model","DOM (Document Object Model)")}} API</li> + <li>Die <a href="https://developer.mozilla.org/en-US/docs/Web/API/Geolocation">Geolocation API</a> ruft geografische Informationen ab. So ist es für <a href="https://www.google.com/maps">Google Maps</a> möglich dein Standort zu ermitteln um es danach z.B. auf einer Karte anzuzeigen.</li> + <li>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API">Canvas</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API">WebGL</a> APIs ermöglichen es dir, 2D oder 3D animierte Grafiken zu erstellen. Das ermöglicht die Darstellung und den Einsatz von Webtechnologien. Mehr kannst du unter <a href="https://www.chromeexperiments.com/webgl">Chrome Experiments</a> und <a href="http://webglsamples.org/">webglsamples</a> erfahren.</li> + <li><a href="https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery">Audio and Video APIs</a> beispielsweise {{domxref("HTMLMediaElement")}} und <a href="/en-US/docs/Web/API/WebRTC_API">WebRTC</a> ermöglichen es wirklich spannende Dinge multimedial zu erstellen. Beispielsweise können Audio und Video in eine Webseite integriert werden, Ebenso ist es möglich die Webcam aufzunehmen und sie danach wiederzugeben. (Probiere unser einfaches <a href="http://chrisdavidmills.github.io/snapshot/">Snapshot Beispiel</a> um eine Einblick zu bekommen).</li> +</ul> + +<div class="note"> +<p><strong>Notiz: </strong>Viele der oben genannten Beispiele funktionieren in älteren Browsern nicht — wenn du dein Code ausprobieren willst, dann ist es eine gute Idee einen Modernen Browser wie Firefox, Chrome, Edge oder Opera zu benutzen. Es wird trotzdem nötig sein, sich mit <a href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing">Cross Browser Testing</a> auseinander zu setzen, wenn es näher an eine Produktionssystem gehen soll(z.B. Echter Code die echte Kunden benutzen sollen).</p> +</div> + +<p><strong>Drittanbieter-APIs</strong>sind nicht standardmäßig im Browser integriert, und du wirst großenteils deren Code und Informationen von wo anders finden müssen. Zum Beispiel</p> + +<ul> + <li>Die <a href="https://dev.twitter.com/overview/documentation">Twitter API</a>erlaubt es dir Dinge, wie die aktuellsten Tweets auf deiner Webseite anzeigen zu lassen.</li> + <li><a href="https://developers.google.com/maps/">Google Maps API</a>erlaubt es dir, eigene Karten auf deiner Webseite anzeigen zu lassen oder andere ähnliche Funktionen zu benutzen</li> +</ul> + +<div class="note"> +<p><strong>Notiz: </strong>Diese APIs sind sehr fortschrittlich und werden in diesem Modul nicht weiter behandelt.Du findest weitere Informationen bei unseren Modul<a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs">Clientbasierte Web APIs Modul</a>.</p> +</div> + +<p>Es sind noch viele weitere APIs Verfügbar! Trotzdem werde jetzt nicht zu aufgeregt, denn du wirst es nicht schaffen, das nächste Facebook, Google Maps, oder Instagram zu entwickeln, nach gerade mal 24 Stunden JavaScript lernen — es gibt nämlich noch viele Sachen die Behandelt werden müssen. Und deswegen bist du hier — also lass uns weiter machen!</p> + +<h2 id="Was_genau_macht_JavaScript_auf_deiner_Webseite">Was genau macht JavaScript auf deiner Webseite?</h2> + +<p>Here we'll start actually looking at some code, and while doing so explore what actually happens when you run some JavaScript in your page.</p> + +<p>Let's briefly recap the story of what happens when you load a web page in a browser (first talked about in our <a href="/en-US/Learn/CSS/Introduction_to_CSS/How_CSS_works#How_does_CSS_actually_work">How CSS works</a> article). When you load a web page in your browser, you are running your code (the HTML, CSS, and JavaScript) inside an execution environment (the browser tab). This is like a factory that takes in raw materials (the code) and outputs a product (the web page).</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13504/execution.png" style="display: block; margin: 0 auto;"></p> + +<p>The JavaScript is executed by the browser's JavaScript engine, after the HTML and CSS have been assembled and put together into a web page. This ensures that the structure and style of the page are already in place by the time the JavaScript starts to run.</p> + +<p>This is a good thing, as a very common use of JavaScript is to dynamically modify HTML and CSS to update a user interface, via the Document Object Model API (as mentioned above). If the JavaScript loaded and tried to run before the HTML and CSS was there to affect, then errors would occur.</p> + +<h3 id="Browser_Sicherheit">Browser Sicherheit</h3> + +<p>Each browser tab is its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab — or on another website. This is a good security measure — if this were not the case, then pirates could start writing code to steal information from other websites, and other such bad things.</p> + +<div class="note"> +<p><strong>Note</strong>: There are ways to send code and data between different websites/tabs in a safe manner, but these are advanced techniques that we won't cover in this course.</p> +</div> + +<h3 id="JavaScript_running_order">JavaScript running order</h3> + +<p>When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom. This means that you need to be careful what order you put things in. For example, let's return to the block of JavaScript we saw in our first example:</p> + +<pre class="brush: js notranslate">var para = document.querySelector('p'); + +para.addEventListener('click', updateName); + +function updateName() { + var name = prompt('Enter a new name'); + para.textContent = 'Player 1: ' + name; +}</pre> + +<p>Here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph is clicked, the <code>updateName()</code> code block (lines 5–8) is run. The <code>updateName()</code> code block (these types of reusable code block are called "functions") asks the user for a new name, and then inserts that name into the paragraph to update the display.</p> + +<p>If you swapped the order of the first two lines of code, it would no longer work — instead, you'd get an error returned in the browser developer console — <code>TypeError: para is undefined</code>. This means that the <code>para</code> object does not exist yet, so we can't add an event listener to it.</p> + +<div class="note"> +<p><strong>Note</strong>: This is a very common error — you need to be careful that the objects referenced in your code exist before you try to do stuff to them.</p> +</div> + +<h3 id="Interpreted_versus_compiled_code">Interpreted versus compiled code</h3> + +<p>You might hear the terms <strong>interpreted</strong> and <strong>compiled</strong> in the context of programming. JavaScript is an interpreted language — the code is run from top to bottom and the result of running the code is immediately returned. You don't have to transform the code into a different form before the browser runs it.</p> + +<p>Compiled languages on the other hand are transformed (compiled) into another form before they are run by the computer. For example C/C++ are compiled into assembly language that is then run by the computer.</p> + +<p>Both approaches have different advantages, which we won't discuss at this point.</p> + +<h3 id="Server-side_versus_client-side_code">Server-side versus client-side code</h3> + +<p>You might also hear the terms <strong>server-side</strong> and <strong>client-side</strong> code, specially in the context of web development. Client-side code is code that is run on the user's computer — when a web page is viewed, the page's client-side code is downloaded, then run and displayed by the browser. In this JavaScript module we are explicitly talking about <strong>client-side JavaScript</strong>.</p> + +<p>Server-side code on the other hand is run on the server, then its results are downloaded and displayed in the browser. Examples of popular server-side web languages include PHP, Python, Ruby, and ASP.NET. And JavaScript! JavaScript can also be used as a server-side language, for example in the popular Node.js environment — you can find more out about server-side JavaScript in our <a href="/en-US/docs/Learn/Server-side">Dynamic Websites – Server-side programming</a> topic.</p> + +<p>The word <strong>dynamic</strong> is used to describe both client-side JavaScript, and server-side languages — it refers to the ability to update the display of a web page/app to show different things in different circumstances, generating new content as required. Server-side code dynamically generates new content on the server, e.g. pulling data from a database, whereas client-side JavaScript dynamically generates new content inside the browser on the client, e.g. creating a new HTML table, inserting data requested from the server into it, then displaying the table in a web page shown to the user. The meaning is slightly different in the two contexts, but related, and both approaches (server-side and client-side) usually work together.</p> + +<p>A web page with no dynamically updating content is referred to as <strong>static</strong> — it just shows the same content all the time.</p> + +<h2 id="How_do_you_add_JavaScript_to_your_page">How do you add JavaScript to your page?</h2> + +<p>JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses {{htmlelement("link")}} elements to apply external stylesheets and {{htmlelement("style")}} elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML — the {{htmlelement("script")}} element. Let's learn how this works.</p> + +<h3 id="Internal_JavaScript">Internal JavaScript</h3> + +<ol> + <li>First of all, make a local copy of our example file <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/what-is-js/apply-javascript.html">apply-javascript.html</a>. Save it in a directory somewhere sensible.</li> + <li>Open the file in your web browser and in your text editor. You'll see that the HTML creates a simple web page containing a clickable button.</li> + <li>Next, go to your text editor and add the following just before your closing <code></body></code> tag: + <pre class="brush: html notranslate"><script> + + // JavaScript goes here + +</script></pre> + </li> + <li>Now we'll add some JavaScript inside our {{htmlelement("script")}} element to make the page do something more interesting — add the following code just below the "// JavaScript goes here" line: + <pre class="brush: js notranslate">function createParagraph() { + var para = document.createElement('p'); + para.textContent = 'You clicked the button!'; + document.body.appendChild(para); +} + +var buttons = document.querySelectorAll('button'); + +for (var i = 0; i < buttons.length ; i++) { + buttons[i].addEventListener('click', createParagraph); +}</pre> + </li> + <li>Save your file and refresh the browser — now you should see that when you click the button, a new paragraph is generated and placed below.</li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: If your example doesn't seem to work, go through the steps again and check that you did everything right. Did you save your local copy of the starting code as a <code>.html</code> file? Did you add your {{htmlelement("script")}} element just before the <code></body></code> tag? Did you enter the JavaScript exactly as shown? <strong>JavaScript is case sensitive, and very fussy, so you need to enter the syntax exactly as shown, otherwise it may not work.</strong></p> +</div> + +<div class="note"> +<p><strong>Note</strong>: You can see this version on GitHub as <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/what-is-js/apply-javascript-internal.html">apply-javascript-internal.html</a> (<a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/what-is-js/apply-javascript-internal.html">see it live too</a>).</p> +</div> + +<h3 id="External_JavaScript">External JavaScript</h3> + +<p>This works great, but what if we wanted to put our JavaScript in an external file? Let's explore this now.</p> + +<ol> + <li>First, create a new file in the same directory as your sample HTML file. Call it <code>script.js</code> — make sure it has that .js filename extension, as that's how it is recognized as JavaScript.</li> + <li>Next, copy all of the script out of your current {{htmlelement("script")}} element and paste it into the .js file. Save that file.</li> + <li>Now replace your current {{htmlelement("script")}} element with the following: + <pre class="brush: html notranslate"><script src="script.js"></script></pre> + </li> + <li>Save and refresh your browser, and you should see the same thing! It works just the same, but now we've got the JavaScript in an external file. This is generally a good thing in terms of organizing your code, and making it reusable across multiple HTML files. Plus the HTML is easier to read without huge chunks of script dumped in it.</li> +</ol> + +<p><strong>Note</strong>: You can see this version on GitHub as <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/what-is-js/apply-javascript-external.html">apply-javascript-external.html</a> and <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/what-is-js/script.js">script.js</a> (<a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/what-is-js/apply-javascript-external.html">see it live too</a>).</p> + +<h3 id="Inline_JavaScript_handlers">Inline JavaScript handlers</h3> + +<p>Note that sometimes you'll come across bits of actual JavaScript code living inside HTML. It might look something like this:</p> + +<pre class="brush: js example-bad notranslate">function createParagraph() { + var para = document.createElement('p'); + para.textContent = 'You clicked the button!'; + document.body.appendChild(para); +}</pre> + +<pre class="brush: html example-bad notranslate"><button onclick="createParagraph()">Click me!</button></pre> + +<p>You can try this version of our demo below.</p> + +<p>{{ EmbedLiveSample('Inline_JavaScript_handlers', '100%', 150) }}</p> + +<p>This demo has exactly the same functionality as in the previous two sections, except that the {{htmlelement("button")}} element includes an inline <code>onclick</code> handler to make the function run when the button is pressed.</p> + +<p><strong>Please don't do this, however.</strong> It is bad practice to pollute your HTML with JavaScript, and it is inefficient — you'd have to include the <code>onclick="createParagraph()"</code> attribute on every button you wanted the JavaScript to apply to.</p> + +<p>Using a pure JavaScript construct allows you to select all the buttons using one instruction. The code we used above to serve this purpose looks like this:</p> + +<pre class="notranslate">var buttons = document.querySelectorAll('button'); + +for (var i = 0; i < buttons.length ; i++) { + buttons[i].addEventListener('click', createParagraph); +}</pre> + +<p>This might look a bit longer than the <code>onclick</code> attribute, but this will work for all buttons no matter how many are on the page, and how many are added or removed. The JavaScript does not need to be changed.</p> + +<div class="note"> +<p><strong>Note</strong>: Try editing your version of <code>apply-javascript.html</code> and add a few more buttons into the file. When you reload, you should find that all of the buttons when clicked will create a paragraph. Neat, huh?</p> +</div> + +<h2 id="Comments">Comments</h2> + +<p>As with HTML and CSS, it is possible to write comments into your JavaScript code that will be ignored by the browser, and exist simply to provide instructions to your fellow developers on how the code works (and you, if you come back to your code after 6 months and can't remember what you did). Comments are very useful, and you should use them often, particularly for larger applications. There are two types:</p> + +<ul> + <li>A single line comment is written after a double forward slash (//), e.g. + <pre class="brush: js notranslate">// I am a comment</pre> + </li> + <li>A multi-line comment is written between the strings /* and */, e.g. + <pre class="brush: js notranslate">/* + I am also + a comment +*/</pre> + </li> +</ul> + +<p>So for example, we could annotate our last demo's JavaScript with comments like so:</p> + +<pre class="brush: js notranslate">// Function: creates a new paragraph and append it to the bottom of the HTML body. + +function createParagraph() { + var para = document.createElement('p'); + para.textContent = 'You clicked the button!'; + document.body.appendChild(para); +} + +/* + 1. Get references to all the buttons on the page and sort them in an array. + 2. Loop through all the buttons and add a click event listener to each one. + + When any button is pressed, the createParagraph() function will be run. +*/ + +var buttons = document.querySelectorAll('button'); + +for (var i = 0; i < buttons.length ; i++) { + buttons[i].addEventListener('click', createParagraph); +}</pre> + +<h2 id="Summary">Summary</h2> + +<p>So there you go, your first step into the world of JavaScript. We've begun with just theory, to start getting you used to why you'd use JavaScript, and what kind of things you can do with it. Along the way you saw a few code examples and learned how JavaScript fits in with the rest of the code on your website, amongst other things.</p> + +<p>JavaScript may seem a bit daunting right now, but don't worry — in this course we will take you through it in simple steps that will make sense going forward. In the next article we will <a href="/en-US/docs/Learn/JavaScript/Introduction_to_JavaScript_1/A_first_splash">plunge straight into the practical</a>, getting you to jump straight in and build your own JavaScript examples.</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><strong><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript">What is JavaScript?</a></strong></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/A_first_splash">A first splash into JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables">Storing the information you need — Variables</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math">Basic math in JavaScript — numbers and operators</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Assessment: Silly story generator</a></li> +</ul> + +<p>{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}</p> |