aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/learn/javascript
diff options
context:
space:
mode:
Diffstat (limited to 'files/zh-tw/learn/javascript')
-rw-r--r--files/zh-tw/learn/javascript/building_blocks/build_your_own_function/index.html246
-rw-r--r--files/zh-tw/learn/javascript/building_blocks/conditionals/index.html789
-rw-r--r--files/zh-tw/learn/javascript/building_blocks/functions/index.html396
-rw-r--r--files/zh-tw/learn/javascript/building_blocks/image_gallery/index.html135
-rw-r--r--files/zh-tw/learn/javascript/building_blocks/index.html52
-rw-r--r--files/zh-tw/learn/javascript/building_blocks/looping_code/index.html928
-rw-r--r--files/zh-tw/learn/javascript/building_blocks/return_values/index.html172
-rw-r--r--files/zh-tw/learn/javascript/client-side_web_apis/index.html39
-rw-r--r--files/zh-tw/learn/javascript/client-side_web_apis/manipulating_documents/index.html314
-rw-r--r--files/zh-tw/learn/javascript/first_steps/a_first_splash/index.html706
-rw-r--r--files/zh-tw/learn/javascript/first_steps/arrays/index.html571
-rw-r--r--files/zh-tw/learn/javascript/first_steps/index.html71
-rw-r--r--files/zh-tw/learn/javascript/first_steps/math/index.html426
-rw-r--r--files/zh-tw/learn/javascript/first_steps/silly_story_generator/index.html149
-rw-r--r--files/zh-tw/learn/javascript/first_steps/strings/index.html352
-rw-r--r--files/zh-tw/learn/javascript/first_steps/useful_string_methods/index.html714
-rw-r--r--files/zh-tw/learn/javascript/first_steps/variables/index.html344
-rw-r--r--files/zh-tw/learn/javascript/first_steps/what_is_javascript/index.html425
-rw-r--r--files/zh-tw/learn/javascript/first_steps/what_went_wrong/index.html253
-rw-r--r--files/zh-tw/learn/javascript/howto/index.html294
-rw-r--r--files/zh-tw/learn/javascript/index.html71
-rw-r--r--files/zh-tw/learn/javascript/objects/adding_bouncing_balls_features/index.html184
-rw-r--r--files/zh-tw/learn/javascript/objects/basics/index.html243
-rw-r--r--files/zh-tw/learn/javascript/objects/index.html42
-rw-r--r--files/zh-tw/learn/javascript/objects/inheritance/index.html210
-rw-r--r--files/zh-tw/learn/javascript/objects/json/index.html325
-rw-r--r--files/zh-tw/learn/javascript/objects/object-oriented_js/index.html277
-rw-r--r--files/zh-tw/learn/javascript/objects/object_building_practice/index.html283
-rw-r--r--files/zh-tw/learn/javascript/objects/object_prototypes/index.html236
29 files changed, 9247 insertions, 0 deletions
diff --git a/files/zh-tw/learn/javascript/building_blocks/build_your_own_function/index.html b/files/zh-tw/learn/javascript/building_blocks/build_your_own_function/index.html
new file mode 100644
index 0000000000..80b134992a
--- /dev/null
+++ b/files/zh-tw/learn/javascript/building_blocks/build_your_own_function/index.html
@@ -0,0 +1,246 @@
+---
+title: 建立自己的功能函數
+slug: Learn/JavaScript/Building_blocks/Build_your_own_function
+translation_of: Learn/JavaScript/Building_blocks/Build_your_own_function
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Functions","Learn/JavaScript/Building_blocks/Return_values", "Learn/JavaScript/Building_blocks")}}</div>
+
+<p class="summary">通過前一篇文章中討論的大部分基本理論,本文提供了實踐經驗。 在這裡,您將學習構建自己的自定義功能函數。 在此過程中,我們還將解釋處理函數的一些有用細節。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">Prerequisites:</th>
+ <td>Basic computer literacy, a basic understanding of HTML and CSS, <a href="/en-US/docs/Learn/JavaScript/First_steps">JavaScript first steps</a>, <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">Functions — reusable blocks of code</a>.</td>
+ </tr>
+ <tr>
+ <th scope="row">Objective:</th>
+ <td>To provide some practice in building a custom function, and explain a few more useful associated details.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Active_learning_Let's_build_a_function">Active learning: Let's build a function</h2>
+
+<p>The custom function we are going to build will be called <code>displayMessage()</code>. It will display a custom message box on a web page and will act as a customized replacement for a browser's built-in <a href="/en-US/docs/Web/API/Window/alert">alert()</a> function. We've seen this before, but let's just refresh our memories. Type the following in your browser's JavaScript console, on any page you like:</p>
+
+<pre class="brush: js">alert('This is a message');</pre>
+
+<p>The <code>alert</code> function takes a single argument — the string that is displayed in the alert box. Try varying the string to change the message.</p>
+
+<p>The <code>alert</code> function is limited: you can alter the message, but you can't easily vary anything else, such as the color, icon, or anything else. We'll build one that will prove to be more fun.</p>
+
+<div class="note">
+<p><strong>Note</strong>: This example should work in all modern browsers fine, but the styling might look a bit funny in slightly older browsers. We'd recommend you doing this exercise in a modern browser like Firefox, Opera, or Chrome.</p>
+</div>
+
+<h2 id="The_basic_function">The basic function</h2>
+
+<p>To begin with, let's put together a basic function.</p>
+
+<div class="note">
+<p><strong>Note</strong>: For function naming conventions, you should follow the same rules as <a href="/en-US/Learn/JavaScript/First_steps/Variables#An_aside_on_variable_naming_rules">variable naming conventions</a>. This is fine, as you can tell them apart — function names appear with parentheses after them, and variables don't.</p>
+</div>
+
+<ol>
+ <li>Start by accessing the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/functions/function-start.html">function-start.html</a> file and making a local copy. You'll see that the HTML is simple — the body contains just a single button. We've also provided some basic CSS to style the custom message box, and an empty {{htmlelement("script")}} element to put our JavaScript in.</li>
+ <li>Next, add the following inside the <code>&lt;script&gt;</code> element:
+ <pre class="brush: js">function displayMessage() {
+
+}</pre>
+ We start off with the keyword <code>function</code>, which means we are defining a function. This is followed by the name we want to give to our function, a set of parentheses, and a set of curly braces. Any parameters we want to give to our function go inside the parentheses, and the code that runs when we call the function goes inside the curly braces.</li>
+ <li>Finally, add the following code inside the curly braces:
+ <pre class="brush: js">var html = document.querySelector('html');
+
+var panel = document.createElement('div');
+panel.setAttribute('class', 'msgBox');
+html.appendChild(panel);
+
+var msg = document.createElement('p');
+msg.textContent = 'This is a message box';
+panel.appendChild(msg);
+
+var closeBtn = document.createElement('button');
+closeBtn.textContent = 'x';
+panel.appendChild(closeBtn);
+
+closeBtn.onclick = function() {
+ panel.parentNode.removeChild(panel);
+}</pre>
+ </li>
+</ol>
+
+<p>This is quite a lot of code to go through, so we'll walk you through it bit by bit.</p>
+
+<p>The first line uses a DOM API function called {{domxref("document.querySelector()")}} to select the {{htmlelement("html")}} element and store a reference to it in a variable called <code>html</code>, so we can do things to it later on:</p>
+
+<pre class="brush: js">var html = document.querySelector('html');</pre>
+
+<p>The next section uses another DOM API function called {{domxref("Document.createElement()")}} to create a {{htmlelement("div")}} element and store a reference to it in a variable called <code>panel</code>. This element will be the outer container of our message box.</p>
+
+<p>We then use yet another DOM API function called {{domxref("Element.setAttribute()")}} to set a <code>class</code> attribute on our panel with a value of <code>msgBox</code>. This is to make it easier to style the element — if you look at the CSS on the page, you'll see that we are using a <code>.msgBox</code> class selector to style the message box and its contents.</p>
+
+<p>Finally, we call a DOM function called {{domxref("Node.appendChild()")}} on the <code>html</code> variable we stored earlier, which nests one element inside the other as a child of it. We specify the panel <code>&lt;div&gt;</code> as the child we want to append inside the <code>&lt;html&gt;</code> element. We need to do this as the element we created won't just appear on the page on its own — we need to specify where to put it.</p>
+
+<pre class="brush: js">var panel = document.createElement('div');
+panel.setAttribute('class', 'msgBox');
+html.appendChild(panel);</pre>
+
+<p>The next two sections make use of the same <code>createElement()</code> and <code>appendChild()</code> functions we've already seen to create two new elements — a {{htmlelement("p")}} and a {{htmlelement("button")}} — and insert them in the page as children of the panel <code>&lt;div&gt;</code>. We use their {{domxref("Node.textContent")}} property — which represents the text content of an element — to insert a message inside the paragraph, and an 'x' inside the button. This button will be what needs to be clicked/activated when the user wants to close the message box.</p>
+
+<pre class="brush: js">var msg = document.createElement('p');
+msg.textContent = 'This is a message box';
+panel.appendChild(msg);
+
+var closeBtn = document.createElement('button');
+closeBtn.textContent = 'x';
+panel.appendChild(closeBtn);</pre>
+
+<p>Finally, we use an {{domxref("GlobalEventHandlers.onclick")}} event handler to make it so that when the button is clicked, some code is run to delete the whole panel from the page — to close the message box.</p>
+
+<p>Briefly, the <code>onclick</code> handler is a property available on the button (or in fact, any element on the page) that can be set to a function to specify what code to run when the button is clicked. You'll learn a lot more about these in our later events article. We are making the <code>onclick</code> handler equal to an anonymous function, which contains the code to run when the button is clicked. The line inside the function uses the {{domxref("Node.removeChild()")}} DOM API function to specify that we want to remove a specific child element of the HTML element — in this case the panel <code>&lt;div&gt;</code>.</p>
+
+<pre class="brush: js">closeBtn.onclick = function() {
+ panel.parentNode.removeChild(panel);
+}</pre>
+
+<p>Basically, this whole block of code is generating a block of HTML that looks like so, and inserting it into the page:</p>
+
+<pre class="brush: html">&lt;div class="msgBox"&gt;
+ &lt;p&gt;This is a message box&lt;/p&gt;
+ &lt;button&gt;x&lt;/button&gt;
+&lt;/div&gt;</pre>
+
+<p>That was a lot of code to work through — don't worry too much if you don't remember exactly how every bit of it works right now! The main part we want to focus on here is the function's structure and usage, but we wanted to show something interesting for this example.</p>
+
+<h2 id="Calling_the_function">Calling the function</h2>
+
+<p>You've now got your function definition written into your <code>&lt;script&gt;</code> element just fine, but it will do nothing as it stands.</p>
+
+<ol>
+ <li>Try including the following line below your function to call it:
+ <pre class="brush: js">displayMessage();</pre>
+ This line invokes the function, making it run immediately. When you save your code and reload it in the browser, you'll see the little message box appear immediately, only once. We are only calling it once, after all.</li>
+ <li>
+ <p>Now open your browser developer tools on the example page, go to the JavaScript console and type the line again there, you'll see it appear again! So this is fun — we now have a reusable function that we can call any time we like.</p>
+
+ <p>But we probably want it to appear in response to user and system actions. In a real application, such a message box would probably be called in response to new data being available, or an error having occurred, or the user trying to delete their profile ("are you sure about this?"), or the user adding a new contact and the operation completing successfully ... etc.</p>
+
+ <p>In this demo, we'll get the message box to appear when the user clicks the button.</p>
+ </li>
+ <li>Delete the previous line you added.</li>
+ <li>Next, we'll select the button and store a reference to it in a variable. Add the following line to your code, above the function definition:
+ <pre class="brush: js">var btn = document.querySelector('button');</pre>
+ </li>
+ <li>Finally, add the following line below the previous one:
+ <pre class="brush: js">btn.onclick = displayMessage;</pre>
+ In a similar way to our <code>closeBtn.onclick...</code> line inside the function, here we are calling some code in response to a button being clicked. But in this case, instead of calling an anonymous function containing some code, we are calling our function name directly.</li>
+ <li>Try saving and refreshing the page — now you should see the message box appear when you click the button.</li>
+</ol>
+
+<p>You might be wondering why we haven't included the parentheses after the function name. This is because we don't want to call the function immediately — only after the button has been clicked. If you try changing the line to</p>
+
+<pre class="brush: js">btn.onclick = displayMessage();</pre>
+
+<p>and saving and reloading, you'll see that the message box appears without the button being clicked! The parentheses in this context are sometimes called the "function invocation operator". You only use them when you want to run the function immediately in the current scope. In the same respect, the code inside the anonymous function is not run immediately, as it is inside the function scope.</p>
+
+<p>If you tried the last experiment, make sure to undo the last change before carrying on.</p>
+
+<h2 id="Improving_the_function_with_parameters">Improving the function with parameters</h2>
+
+<p>As it stands, the function is still not very useful — we don't want to just show the same default message every time. Let's improve our function by adding some parameters, allowing us to call it with some different options.</p>
+
+<ol>
+ <li>First of all, update the first line of the function:
+ <pre class="brush: js">function displayMessage() {</pre>
+ to this:
+
+ <pre class="brush: js">function displayMessage(msgText, msgType) {</pre>
+ Now when we call the function, we can provide two variable values inside the parentheses to specify the message to display in the message box, and the type of message it is.</li>
+ <li>To make use of the first parameter, update the following line inside your function:
+ <pre class="brush: js">msg.textContent = 'This is a message box';</pre>
+ to
+
+ <pre class="brush: js">msg.textContent = msgText;</pre>
+ </li>
+ <li>Last but not least, you now need to update your function call to include some updated message text. Change the following line:
+ <pre class="brush: js">btn.onclick = displayMessage;</pre>
+ to this block:
+
+ <pre class="brush: js">btn.onclick = function() {
+ displayMessage('Woo, this is a different message!');
+};</pre>
+ If we want to specify parameters inside parentheses for the function we are calling, then we can't call it directly — we need to put it inside an anonymous function so that it isn't in the immediate scope and therefore isn't called immediately. Now it will not be called until the button is clicked.</li>
+ <li>Reload and try the code again and you'll see that it still works just fine, except that now you can also vary the message inside the parameter to get different messages displayed in the box!</li>
+</ol>
+
+<h3 id="A_more_complex_parameter">A more complex parameter</h3>
+
+<p>On to the next parameter. This one is going to involve slightly more work — we are going to set it so that depending on what the <code>msgType</code> parameter is set to, the function will display a different icon and a different background color.</p>
+
+<ol>
+ <li>First of all, download the icons needed for this exercise (<a href="https://raw.githubusercontent.com/mdn/learning-area/master/javascript/building-blocks/functions/icons/warning.png">warning</a> and <a href="https://raw.githubusercontent.com/mdn/learning-area/master/javascript/building-blocks/functions/icons/chat.png">chat</a>) from GitHub. Save them in a new folder called <code>icons</code> in the same location as your HTML file.
+
+ <div class="note"><strong>Note</strong>: <a href="https://www.iconfinder.com/icons/1031466/alarm_alert_error_warning_icon">warning</a> and <a href="https://www.iconfinder.com/icons/1031441/chat_message_text_icon">chat</a> icons found on iconfinder.com, and designed by <a href="https://www.iconfinder.com/nazarr">Nazarrudin Ansyari</a>. Thanks!</div>
+ </li>
+ <li>Next, find the CSS inside your HTML file. We'll make a few changes to make way for the icons. First, update the <code>.msgBox</code> width from:
+ <pre class="brush: css">width: 200px;</pre>
+ to
+
+ <pre class="brush: css">width: 242px;</pre>
+ </li>
+ <li>Next, add the following lines inside the <code>.msgBox p { ... }</code> rule:
+ <pre class="brush: css">padding-left: 82px;
+background-position: 25px center;
+background-repeat: no-repeat;</pre>
+ </li>
+ <li>Now we need to add code to our <code>displayMessage()</code> function to handle displaying the icons. Add the following block just above the closing curly brace (<code>}</code>) of your function:
+ <pre class="brush: js">if (msgType === 'warning') {
+ msg.style.backgroundImage = 'url(icons/warning.png)';
+ panel.style.backgroundColor = 'red';
+} else if (msgType === 'chat') {
+ msg.style.backgroundImage = 'url(icons/chat.png)';
+ panel.style.backgroundColor = 'aqua';
+} else {
+ msg.style.paddingLeft = '20px';
+}</pre>
+ Here, if the <code>msgType</code> parameter is set as <code>'warning'</code>, the warning icon is displayed and the panel's background color is set to red. If it is set to <code>'chat'</code>, the chat icon is displayed and the panel's background color is set to aqua blue. If the <code>msgType</code> parameter is not set at all (or to something different), then the <code>else { ... }</code> part of the code comes into play, and the paragraph is simply given default padding and no icon, with no background panel color set either. This provides a default state if no <code>msgType</code> parameter is provided, meaning that it is an optional parameter!</li>
+ <li>Let's test out our updated function, try updating the <code>displayMessage()</code> call from this:
+ <pre class="brush: js">displayMessage('Woo, this is a different message!');</pre>
+ to one of these:
+
+ <pre class="brush: js">displayMessage('Your inbox is almost full — delete some mails', 'warning');
+displayMessage('Brian: Hi there, how are you today?','chat');</pre>
+ You can see how useful our (now not so) little function is becoming.</li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: If you have trouble getting the example to work, feel free to check your code against the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/functions/function-stage-4.html">finished version on GitHub</a> (<a href="http://mdn.github.io/learning-area/javascript/building-blocks/functions/function-stage-4.html">see it running live</a> also), or ask us for help.</p>
+</div>
+
+<h2 id="Conclusion">Conclusion</h2>
+
+<p>Congratulations on reaching the end! This article took you through the entire process of building up a practical custom function, which with a bit more work could be transplanted into a real project. In the next article we'll wrap up functions by explaining another essential related concept — return values.</p>
+
+<ul>
+</ul>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Functions","Learn/JavaScript/Building_blocks/Return_values", "Learn/JavaScript/Building_blocks")}}</p>
+
+<p> </p>
+
+<h2 id="In_this_module">In this module</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals">Making decisions in your code — conditionals</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code">Looping code</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">Functions — reusable blocks of code</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Build_your_own_function">Build your own function</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Return_values">Function return values</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events">Introduction to events</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Image_gallery">Image gallery</a></li>
+</ul>
+
+<p> </p>
diff --git a/files/zh-tw/learn/javascript/building_blocks/conditionals/index.html b/files/zh-tw/learn/javascript/building_blocks/conditionals/index.html
new file mode 100644
index 0000000000..8b63b1034d
--- /dev/null
+++ b/files/zh-tw/learn/javascript/building_blocks/conditionals/index.html
@@ -0,0 +1,789 @@
+---
+title: 在代碼中做出決定 - 條件
+slug: Learn/JavaScript/Building_blocks/conditionals
+translation_of: Learn/JavaScript/Building_blocks/conditionals
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{NextMenu("Learn/JavaScript/Building_blocks/Looping_code", "Learn/JavaScript/Building_blocks")}}</div>
+
+<p class="summary">在任何編程語言中,代碼都需要根據不同的輸入做出決策並相應地執行操作。 例如,在遊戲中,如果玩家的生命數量為0,則遊戲結束。 在天氣應用程序中,如果在早上查看,則顯示日出圖形; 如果是夜晚,則顯示星星和月亮。 在本文中,我們將探討條件結構如何在JavaScript中工作。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">Prerequisites:</th>
+ <td>Basic computer literacy, a basic understanding of HTML and CSS, <a href="/en-US/docs/Learn/JavaScript/First_steps">JavaScript first steps</a>.</td>
+ </tr>
+ <tr>
+ <th scope="row">Objective:</th>
+ <td>To understand how to use conditional structures in JavaScript.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="你可以擁有一個條件..!">你可以擁有一個條件..!</h2>
+
+<p>從小到大,人們(和其它動物)作出決定的時間會影響到他們的生活 ("我應該吃一個或兩個餅乾?")  ("我應該留在我的家鄉並在我父親的農場工作還是應該要到美國研讀天體物理學?")</p>
+
+<p>條件敘述句(Conditional statements)讓我們能將這些決定的過程在Javascript表示出來,從一定得做出的選擇(例如:「吃一個或兩個餅乾」),到這些選擇的結果(或許「吃一個餅乾」會出現「還是會餓」這種結果,而「吃兩個餅乾」的結果會是「吃飽了,但因為吃了全部餅乾而被媽媽罵」)。</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13703/cookie-choice-small.png" style="display: block; margin: 0 auto;"></p>
+
+<h2 id="if_..._else_敘述句">if ... else 敘述句</h2>
+
+<p>讓我們來看Javascript中最常見的條件敘述句 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else">if ... else</a></code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else"> statement</a>.</p>
+
+<h3 id="基本的_if_..._else_語法">基本的 if ... else 語法</h3>
+
+<p>最基本的 <code>if...else</code> 語法看起來像以下 {{glossary("虛擬碼")}}:</p>
+
+<pre>if (condition) {
+ code to run if condition is true
+} else {
+ run some other code instead
+}</pre>
+
+<p>這邊我們可以得知基礎的架構:</p>
+
+<ol>
+ <li>關鍵字 <code>if</code> 和後頭的括號。</li>
+ <li>想測試的條件放在括號中(通常像是「這個值是否大於其他值」或是「這個值是否存在」等等)。這裡的條件會使用先前提過的 <a href="/en-US/Learn/JavaScript/First_steps/Math#Comparison_operators">比較運算子</a>(<a href="/en-US/Learn/JavaScript/First_steps/Math#Comparison_operators">comparison operators</a>),並且最後會回傳 <code>true</code> 或是 <code>false</code>。</li>
+ <li>第一組大括號,在大括號裡面有一些程式碼 — 內容可以是任何我們所需要執行的程式碼,並且只有在條件句回傳 <code>true</code> 才會執行。</li>
+ <li>關鍵字 <code>else</code>。</li>
+ <li>另一組大括號,在大括號中我們一樣是放置所需的程式碼,並只有在條件句回傳 <code>false</code> 才會執行。</li>
+</ol>
+
+<p>這個程式碼的架構很容易理解  — 「如果條件回傳 <code>true</code> ,則執行程式A,否則執行程式B」。</p>
+
+<p>值得注意的是,<code>else</code> 和第二組大括號並不是必要的。如以下範例也能夠執行:</p>
+
+<pre>if (condition) {
+ code to run if condition is true
+}
+
+run some other code</pre>
+
+<p>然而,在這邊有一點要注意:在這個例子中的第二個區塊並沒有被條件式控制,也就是說無論條件式回傳的是 <code>true</code> 或是 <code>false</code>,它都會執行。這並不一定是件壞事,但它可能不會是你要的,通常你可能是想要執行程式碼的一個區塊或是另一塊,而不是兩個都執行。</p>
+
+<p>最後一點,你可能有時候會看到 <code>if...else</code> 敘述是不加大括弧的:</p>
+
+<pre>if (condition) code to run if condition is true
+else run some other code instead</pre>
+
+<p>這當然也是有效的程式碼,但不太建議這樣用。使用大括弧能夠很清楚地看到程式區塊、縮排,也能夠擁有多行程式碼,對於程式的可讀性會提高許多。</p>
+
+<h3 id="A_real_example">A real example</h3>
+
+<p>To understand this syntax better, let's consider a real example. Imagine a child being asked for help with a chore by their mother or father. The parent might say "Hey sweetheart, if you help me by going and doing the shopping, I'll give you some extra allowance so you can afford that toy you wanted." In JavaScript, we could represent this like so:</p>
+
+<pre class="brush: js">var shoppingDone = false;
+
+if (shoppingDone === true) {
+ var childsAllowance = 10;
+} else {
+ var childsAllowance = 5;
+}</pre>
+
+<p>This code as shown will always result in the <code>shoppingDone</code> variable returning <code>false</code>, meaning disappointment for our poor child. It'd be up to us to provide a mechanism for the parent to set the <code>shoppingDone</code> variable to <code>true</code> if the child did the shopping.</p>
+
+<div class="note">
+<p><strong>Note</strong>: You can see a more <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/allowance-updater.html">complete version of this example on GitHub</a> (also see it <a href="http://mdn.github.io/learning-area/javascript/building-blocks/allowance-updater.html">running live</a>.)</p>
+</div>
+
+<h3 id="else_if">else if</h3>
+
+<p>The last example provided us with two choices, or outcomes — but what if we want more than two?</p>
+
+<p>There is a way to chain on extra choices/outcomes to your <code>if...else</code> — using <code>else if</code>. Each extra choice requires an additional block to put in between <code>if() { ... }</code> and <code>else { ... }</code> — check out the following more involved example, which could be part of a simple weather forecast application:</p>
+
+<pre class="brush: html">&lt;label for="weather"&gt;Select the weather type today: &lt;/label&gt;
+&lt;select id="weather"&gt;
+ &lt;option value=""&gt;--Make a choice--&lt;/option&gt;
+ &lt;option value="sunny"&gt;Sunny&lt;/option&gt;
+ &lt;option value="rainy"&gt;Rainy&lt;/option&gt;
+ &lt;option value="snowing"&gt;Snowing&lt;/option&gt;
+ &lt;option value="overcast"&gt;Overcast&lt;/option&gt;
+&lt;/select&gt;
+
+&lt;p&gt;&lt;/p&gt;</pre>
+
+<pre class="brush: js">var select = document.querySelector('select');
+var para = document.querySelector('p');
+
+select.addEventListener('change', setWeather);
+
+function setWeather() {
+ var choice = select.value;
+
+ if (choice === 'sunny') {
+ para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.';
+ } else if (choice === 'rainy') {
+ para.textContent = 'Rain is falling outside; take a rain coat and a brolly, and don\'t stay out for too long.';
+ } else if (choice === 'snowing') {
+ para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.';
+ } else if (choice === 'overcast') {
+ para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.';
+ } else {
+ para.textContent = '';
+ }
+}
+
+</pre>
+
+<p>{{ EmbedLiveSample('else_if', '100%', 100, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<ol>
+ <li>Here we've got an HTML {{htmlelement("select")}} element allowing us to make different weather choices, and a simple paragraph.</li>
+ <li>In the JavaScript, we are storing a reference to both the {{htmlelement("select")}} and {{htmlelement("p")}} elements, and adding an event listener to the <code>&lt;select&gt;</code> element so that when its value is changed, the <code>setWeather()</code> function is run.</li>
+ <li>When this function is run, we first set a variable called <code>choice</code> to the current value selected in the <code>&lt;select&gt;</code> element. We then use a conditional statement to show different text inside the paragraph depending on what the value of <code>choice</code> is. Notice how all the conditions are tested in <code>else if() {...}</code> blocks, except for the first one, which is tested in an <code>if() {...} block</code>.</li>
+ <li>The very last choice, inside the <code>else {...}</code> block, is basically a "last resort" option — the code inside it will be run if none of the conditions are <code>true</code>. In this case, it serves to empty the text out of the paragraph if nothing is selected, for example if a user decides to re-select the "--Make a choice--" placeholder option shown at the beginning.</li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: You can also <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/simple-else-if.html">find this example on GitHub</a> (<a href="http://mdn.github.io/learning-area/javascript/building-blocks/simple-else-if.html">see it running live</a> on there also.)</p>
+</div>
+
+<h3 id="A_note_on_comparison_operators">A note on comparison operators</h3>
+
+<p>Comparison operators are used to test the conditions inside our conditional statements. We first looked at comparison operators back in our <a href="/en-US/Learn/JavaScript/First_steps/Math#Comparison_operators">Basic math in JavaScript — numbers and operators</a> article. Our choices are:</p>
+
+<ul>
+ <li><code>===</code> and <code>!==</code> — test if one value is identical to, or not identical to, another.</li>
+ <li><code>&lt;</code> and <code>&gt;</code> — test if one value is less than or greater than another.</li>
+ <li><code>&lt;=</code> and <code>&gt;=</code> — test if one value is less than or equal to, or greater than or equal to, another.</li>
+</ul>
+
+<div class="note">
+<p><strong>Note</strong>: Review the material at the previous link if you want to refresh your memories on these.</p>
+</div>
+
+<p>We wanted to make a special mention of testing boolean (<code>true</code>/<code>false</code>) values, and a common pattern you'll come across again and again. Any value that is not <code>false</code>, <code>undefined</code>, <code>null</code>, <code>0</code>, <code>NaN</code>, or an empty string (<code>''</code>) actually returns <code>true</code> when tested as a conditional statement, therefore you can simply use a variable name on its own to test whether it is <code>true</code>, or even that it exists (i.e. it is not undefined.) So for example:</p>
+
+<pre class="brush: js">var cheese = 'Cheddar';
+
+if (cheese) {
+ console.log('Yay! Cheese available for making cheese on toast.');
+} else {
+ console.log('No cheese on toast for you today.');
+}</pre>
+
+<p>And, returning to our previous example about the child doing a chore for their parent, you could write it like this:</p>
+
+<pre class="brush: js">var shoppingDone = false;
+
+if (shoppingDone) { // don't need to explicitly specify '=== true'
+ var childsAllowance = 10;
+} else {
+ var childsAllowance = 5;
+}</pre>
+
+<h3 id="Nesting_if_..._else">Nesting if ... else</h3>
+
+<p>It is perfectly OK to put one <code>if...else</code> statement inside another one — to nest them. For example, we could update our weather forecast application to show a further set of choices depending on what the temperature is:</p>
+
+<pre class="brush: js">if (choice === 'sunny') {
+ if (temperature &lt; 86) {
+ para.textContent = 'It is ' + temperature + ' degrees outside — nice and sunny. Let\'s go out to the beach, or the park, and get an ice cream.';
+ } else if (temperature &gt;= 86) {
+ para.textContent = 'It is ' + temperature + ' degrees outside — REALLY HOT! If you want to go outside, make sure to put some suncream on.';
+ }
+}</pre>
+
+<p>Even though the code all works together, each <code>if...else</code> statement works completely independently of the other one.</p>
+
+<h3 id="Logical_operators_AND_OR_and_NOT">Logical operators: AND, OR and NOT</h3>
+
+<p>If you want to test multiple conditions without writing nested <code>if...else</code> statements, <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators">logical operators</a> can help you. When used in conditions, the first two do the following:</p>
+
+<ul>
+ <li><code>&amp;&amp;</code> — AND; allows you to chain together two or more expressions so that all of them have to individually evaluate to <code>true</code> for the whole expression to return <code>true</code>.</li>
+ <li><code>||</code> — OR; allows you to chain together two or more expressions so that one or more of them have to individually evaluate to <code>true</code> for the whole expression to return <code>true</code>.</li>
+</ul>
+
+<p>To give you an AND example, the previous example snippet can be rewritten to this:</p>
+
+<pre class="brush: js">if (choice === 'sunny' &amp;&amp; temperature &lt; 86) {
+ para.textContent = 'It is ' + temperature + ' degrees outside — nice and sunny. Let\'s go out to the beach, or the park, and get an ice cream.';
+} else if (choice === 'sunny' &amp;&amp; temperature &gt;= 86) {
+ para.textContent = 'It is ' + temperature + ' degrees outside — REALLY HOT! If you want to go outside, make sure to put some suncream on.';
+}</pre>
+
+<p>So for example, the first code block will only be run if <code>choice === 'sunny'</code> <em>and</em> <code>temperature &lt; 86</code> return <code>true</code>.</p>
+
+<p>Let's look at a quick OR example:</p>
+
+<pre class="brush: js">if (iceCreamVanOutside || houseStatus === 'on fire') {
+ console.log('You should leave the house quickly.');
+} else {
+ console.log('Probably should just stay in then.');
+}</pre>
+
+<p>The last type of logical operator, NOT, expressed by the <code>!</code> operator, can be used to negate an expression. Let's combine it with OR in the above example:</p>
+
+<pre class="brush: js">if (!(iceCreamVanOutside || houseStatus === 'on fire')) {
+ console.log('Probably should just stay in then.');
+} else {
+ console.log('You should leave the house quickly.');
+}</pre>
+
+<p>In this snippet, if the OR statement returns <code>true</code>, the NOT operator will negate it so that the overall expression returns <code>false</code>.</p>
+
+<p>You can combine as many logical statements together as you want, in whatever structure. The following example executes the code inside only if both OR statements return true, meaning that the overall AND statement will return true:</p>
+
+<pre class="brush: js">if ((x === 5 || y &gt; 3 || z &lt;= 10) &amp;&amp; (loggedIn || userName === 'Steve')) {
+ // run the code
+}</pre>
+
+<p>A common mistake when using the logical OR operator in conditional statements is to try to state the variable whose value you are checking once, and then give a list of values it could be to return true, separated by <code>||</code> (OR) operators. For example:</p>
+
+<pre class="example-bad brush: js">if (x === 5 || 7 || 10 || 20) {
+ // run my code
+}</pre>
+
+<p>In this case the condition inside <code>if(...)</code>  will always evaluate to true since 7 (or any other non-zero value) always evaluates to true. This condition is actually saying "if x equals 5, or 7 is true — which it always is". This is logically not what we want! To make this work you've got to specify a complete test either side of each OR operator:</p>
+
+<pre class="brush: js">if (x === 5 || x === 7 || x === 10 ||x === 20) {
+ // run my code
+}</pre>
+
+<h2 id="switch_statements">switch statements</h2>
+
+<p><code>if...else</code> statements do the job of enabling conditional code well, but they are not without their downsides. They are mainly good for cases where you've got a couple of choices, and each one requires a reasonable amount of code to be run, and/or the conditions are complex (e.g. multiple logical operators). For cases where you just want to set a variable to a certain choice of value or print out a particular statement depending on a condition, the syntax can be a bit cumbersome, especially if you've got a large number of choices.</p>
+
+<p><a href="/en-US/docs/Web/JavaScript/Reference/Statements/switch"><code>switch</code> statements</a> are your friend here — they take a single expression/value as an input, and then look through a number of choices until they find one that matches that value, executing the corresponding code that goes along with it. Here's some more pseudocode, to give you an idea:</p>
+
+<pre>switch (expression) {
+ case choice1:
+ run this code
+ break;
+
+ case choice2:
+ run this code instead
+ break;
+
+ // include as many cases as you like
+
+ default:
+ actually, just run this code
+}</pre>
+
+<p>Here we've got:</p>
+
+<ol>
+ <li>The keyword <code>switch</code>, followed by a set of parentheses.</li>
+ <li>An expression or value inside the parentheses.</li>
+ <li>The keyword <code>case</code>, followed by a choice that the expression/value could be, followed by a colon.</li>
+ <li>Some code to run if the choice matches the expression.</li>
+ <li>A <code>break</code> statement, followed by a semi-colon. If the previous choice matches the expression/value, the browser stops executing the code block here, and moves on to any code that appears below the switch statement.</li>
+ <li>As many other cases (bullets 3–5) as you like.</li>
+ <li>The keyword <code>default</code>, followed by exactly the same code pattern as one of the cases (bullets 3–5), except that <code>default</code> does not have a choice after it, and you don't need to <code>break</code> statement as there is nothing to run after this in the block anyway. This is the default option that runs if none of the choices match.</li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: You don't have to include the <code>default</code> section — you can safely omit it if there is no chance that the expression could end up equaling an unknown value. If there is a chance of this however, you need to include it to handle unknown cases.</p>
+</div>
+
+<h3 id="A_switch_example">A switch example</h3>
+
+<p>Let's have a look at a real example — we'll rewrite our weather forecast application to use a switch statement instead:</p>
+
+<pre class="brush: html">&lt;label for="weather"&gt;Select the weather type today: &lt;/label&gt;
+&lt;select id="weather"&gt;
+ &lt;option value=""&gt;--Make a choice--&lt;/option&gt;
+ &lt;option value="sunny"&gt;Sunny&lt;/option&gt;
+ &lt;option value="rainy"&gt;Rainy&lt;/option&gt;
+ &lt;option value="snowing"&gt;Snowing&lt;/option&gt;
+ &lt;option value="overcast"&gt;Overcast&lt;/option&gt;
+&lt;/select&gt;
+
+&lt;p&gt;&lt;/p&gt;</pre>
+
+<pre class="brush: js">var select = document.querySelector('select');
+var para = document.querySelector('p');
+
+select.addEventListener('change', setWeather);
+
+
+function setWeather() {
+ var choice = select.value;
+
+ switch (choice) {
+ case 'sunny':
+ para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.';
+ break;
+ case 'rainy':
+ para.textContent = 'Rain is falling outside; take a rain coat and a brolly, and don\'t stay out for too long.';
+ break;
+ case 'snowing':
+ para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.';
+ break;
+ case 'overcast':
+ para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.';
+ break;
+ default:
+ para.textContent = '';
+ }
+}</pre>
+
+<p>{{ EmbedLiveSample('A_switch_example', '100%', 100, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<div class="note">
+<p><strong>Note</strong>: You can also <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/simple-switch.html">find this example on GitHub</a> (see it <a href="http://mdn.github.io/learning-area/javascript/building-blocks/simple-switch.html">running live</a> on there also.)</p>
+</div>
+
+<h2 id="三元運算符">三元運算符</h2>
+
+<p>There is one final bit of syntax we want to introduce you to, before we get you to play with some examples. The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">ternary or conditional operator</a> is a small bit of syntax that tests a condition and returns one value/expression if it is <code>true</code>, and another if it is <code>false</code> — this can be useful in some situations, and can take up a lot less code than an <code>if...else</code> block if you simply have two choices that are chosen between via a <code>true</code>/<code>false</code> condition. The pseudocode looks like this:</p>
+
+<pre>( condition ) ? run this code : run this code instead</pre>
+
+<p>So let's look at a simple example:</p>
+
+<pre class="brush: js">var greeting = ( isBirthday ) ? 'Happy birthday Mrs. Smith — we hope you have a great day!' : 'Good morning Mrs. Smith.';</pre>
+
+<p>Here we have a variable called <code>isBirthday</code> — if this is <code>true</code>, we give our guest a happy birthday message; if not, we give her the standard daily greeting.</p>
+
+<h3 id="Ternary_operator_example">Ternary operator example</h3>
+
+<p>You don't just have to set variable values with the ternary operator; you can also run functions, or lines of code — anything you like. The following live example shows a simple theme chooser where the styling for the site is applied using a ternary operator.</p>
+
+<pre class="brush: html">&lt;label for="theme"&gt;Select theme: &lt;/label&gt;
+&lt;select id="theme"&gt;
+ &lt;option value="white"&gt;White&lt;/option&gt;
+ &lt;option value="black"&gt;Black&lt;/option&gt;
+&lt;/select&gt;
+
+&lt;h1&gt;This is my website&lt;/h1&gt;</pre>
+
+<pre class="brush: js">var select = document.querySelector('select');
+var html = document.querySelector('html');
+document.body.style.padding = '10px';
+
+function update(bgColor, textColor) {
+ html.style.backgroundColor = bgColor;
+ html.style.color = textColor;
+}
+
+select.onchange = function() {
+ ( select.value === 'black' ) ? update('black','white') : update('white','black');
+}
+</pre>
+
+<p>{{ EmbedLiveSample('Ternary_operator_example', '100%', 300, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<p>Here we've got a {{htmlelement('select')}} element to choose a theme (black or white), plus a simple {{htmlelement('h1')}} to display a website title. We also have a function called <code>update()</code>, which takes two colors as parameters (inputs). The website's background color is set to the first provided color, and its text color is set to the second provided color.</p>
+
+<p>Finally, we've also got an <a href="/en-US/docs/Web/API/GlobalEventHandlers/onchange">onchange</a> event listener that serves to run a function containing a ternary operator. It starts with a test condition — <code>select.value === 'black'</code>. If this returns <code>true</code>, we run the <code>update()</code> function with parameters of black and white, meaning that we end up with background color of black and text color of white. If it returns <code>false</code>, we run the <code>update()</code> function with parameters of white and black, meaning that the site color are inverted.</p>
+
+<div class="note">
+<p><strong>Note</strong>: You can also <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/simple-ternary.html">find this example on GitHub</a> (see it <a href="http://mdn.github.io/learning-area/javascript/building-blocks/simple-ternary.html">running live</a> on there also.)</p>
+</div>
+
+<h2 id="Active_learning_A_simple_calendar">Active learning: A simple calendar</h2>
+
+<p>In this example you are going to help us finish a simple calendar application. In the code you've got:</p>
+
+<ul>
+ <li>A {{htmlelement("select")}} element to allow the user to choose between different months.</li>
+ <li>An <code>onchange</code> event handler to detect when the value selected in the <code>&lt;select&gt;</code> menu is changed.</li>
+ <li>A function called <code>createCalendar()</code> that draws the calendar and displays the correct month in the {{htmlelement("h1")}} element.</li>
+</ul>
+
+<p>We need you to write a conditional statement inside the <code>onchange</code> handler function, just below the <code>// ADD CONDITIONAL HERE</code> comment. It should:</p>
+
+<ol>
+ <li>Look at the selected month (stored in the <code>choice</code> variable. This will be the <code>&lt;select&gt;</code> element value after the value changes, so "January" for example.)</li>
+ <li>Set a variable called <code>days</code> to be equal to the number of days in the selected month. To do this you'll have to look up the number of days in each month of the year. You can ignore leap years for the purposes of this example.</li>
+</ol>
+
+<p>Hints:</p>
+
+<ul>
+ <li>You are advised to use logical OR to group multiple months together into a single condition; many of them share the same number of days.</li>
+ <li>Think about which number of days is the most common, and use that as a default value.</li>
+</ul>
+
+<p>If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.</p>
+
+<div class="hidden">
+<h6 id="Playable_code">Playable code</h6>
+
+<pre class="brush: html">&lt;h2&gt;Live output&lt;/h2&gt;
+&lt;div class="output" style="height: 500px;overflow: auto;"&gt;
+ &lt;label for="month"&gt;Select month: &lt;/label&gt;
+ &lt;select id="month"&gt;
+ &lt;option value="January"&gt;January&lt;/option&gt;
+ &lt;option value="February"&gt;February&lt;/option&gt;
+ &lt;option value="March"&gt;March&lt;/option&gt;
+ &lt;option value="April"&gt;April&lt;/option&gt;
+ &lt;option value="May"&gt;May&lt;/option&gt;
+ &lt;option value="June"&gt;June&lt;/option&gt;
+ &lt;option value="July"&gt;July&lt;/option&gt;
+ &lt;option value="August"&gt;August&lt;/option&gt;
+ &lt;option value="September"&gt;September&lt;/option&gt;
+ &lt;option value="October"&gt;October&lt;/option&gt;
+ &lt;option value="November"&gt;November&lt;/option&gt;
+ &lt;option value="December"&gt;December&lt;/option&gt;
+ &lt;/select&gt;
+
+ &lt;h1&gt;&lt;/h1&gt;
+
+ &lt;ul&gt;&lt;/ul&gt;
+&lt;/div&gt;
+
+&lt;h2&gt;Editable code&lt;/h2&gt;
+&lt;p class="a11y-label"&gt;Press Esc to move focus away from the code area (Tab inserts a tab character).&lt;/p&gt;
+
+&lt;textarea id="code" class="playable-code" style="height: 400px;width: 95%"&gt;
+var select = document.querySelector('select');
+var list = document.querySelector('ul');
+var h1 = document.querySelector('h1');
+
+select.onchange = function() {
+ var choice = select.value;
+
+ // ADD CONDITIONAL HERE
+
+ createCalendar(days, choice);
+}
+
+function createCalendar(days, choice) {
+ list.innerHTML = '';
+ h1.textContent = choice;
+ for (var i = 1; i &lt;= days; i++) {
+ var listItem = document.createElement('li');
+ listItem.textContent = i;
+ list.appendChild(listItem);
+ }
+}
+
+createCalendar(31,'January');
+&lt;/textarea&gt;
+
+&lt;div class="playable-buttons"&gt;
+ &lt;input id="reset" type="button" value="Reset"&gt;
+ &lt;input id="solution" type="button" value="Show solution"&gt;
+&lt;/div&gt;
+</pre>
+
+<pre class="brush: css">.output * {
+ box-sizing: border-box;
+}
+
+.output ul {
+ padding-left: 0;
+}
+
+.output li {
+ display: block;
+ float: left;
+ width: 25%;
+ border: 2px solid white;
+ padding: 5px;
+ height: 40px;
+ background-color: #4A2DB6;
+ color: white;
+}
+
+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">var textarea = document.getElementById('code');
+var reset = document.getElementById('reset');
+var solution = document.getElementById('solution');
+var code = textarea.value;
+var 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();
+});
+
+var jsSolution = 'var select = document.querySelector(\'select\');\nvar list = document.querySelector(\'ul\');\nvar h1 = document.querySelector(\'h1\');\n\nselect.onchange = function() {\n var choice = select.value;\n var days = 31;\n if(choice === \'February\') {\n days = 28;\n } else if(choice === \'April\' || choice === \'June\' || choice === \'September\'|| choice === \'November\') {\n days = 30;\n }\n\n createCalendar(days, choice);\n}\n\nfunction createCalendar(days, choice) {\n list.innerHTML = \'\';\n h1.textContent = choice;\n for(var i = 1; i &lt;= days; i++) {\n var listItem = document.createElement(\'li\');\n listItem.textContent = i;\n list.appendChild(listItem);\n }\n }\n\ncreateCalendar(31,\'January\');';
+var 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) {
+ var scrollPos = textarea.scrollTop;
+ var caretPos = textarea.selectionStart;
+
+ var front = (textarea.value).substring(0, caretPos);
+ var 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%', 1110, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<h2 id="Active_learning_More_color_choices!">Active learning: More color choices!</h2>
+
+<p>In this example you are going to take the ternary operator example we saw earlier and convert the ternary operator into a switch statement that will allow us to apply more choices to the simple website. Look at the {{htmlelement("select")}} — this time you'll see that it has not two theme options, but five. You need to add a switch statement just underneath the <code>// ADD SWITCH STATEMENT</code> comment:</p>
+
+<ul>
+ <li>It should accept the <code>choice</code> variable as its input expression.</li>
+ <li>For each case, the choice should equal one of the possible values that can be selected, i.e. white, black, purple, yellow, or psychedelic.</li>
+ <li>For each case, the <code>update()</code> function should be run, and be passed two color values, the first one for the background color, and the second one for the text color. Remember that color values are strings, so need to be wrapped in quotes.</li>
+</ul>
+
+<p>If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.</p>
+
+<div class="hidden">
+<h6 id="Playable_code_2">Playable code 2</h6>
+
+<pre class="brush: html">&lt;h2&gt;Live output&lt;/h2&gt;
+&lt;div class="output" style="height: 300px;"&gt;
+ &lt;label for="theme"&gt;Select theme: &lt;/label&gt;
+ &lt;select id="theme"&gt;
+ &lt;option value="white"&gt;White&lt;/option&gt;
+ &lt;option value="black"&gt;Black&lt;/option&gt;
+ &lt;option value="purple"&gt;Purple&lt;/option&gt;
+ &lt;option value="yellow"&gt;Yellow&lt;/option&gt;
+ &lt;option value="psychedelic"&gt;Psychedelic&lt;/option&gt;
+ &lt;/select&gt;
+
+ &lt;h1&gt;This is my website&lt;/h1&gt;
+&lt;/div&gt;
+
+&lt;h2&gt;Editable code&lt;/h2&gt;
+&lt;p class="a11y-label"&gt;Press Esc to move focus away from the code area (Tab inserts a tab character).&lt;/p&gt;
+
+&lt;textarea id="code" class="playable-code" style="height: 450px;width: 95%"&gt;
+var select = document.querySelector('select');
+var html = document.querySelector('.output');
+
+select.onchange = function() {
+ var choice = select.value;
+
+ // ADD SWITCH STATEMENT
+}
+
+function update(bgColor, textColor) {
+ html.style.backgroundColor = bgColor;
+ html.style.color = textColor;
+}&lt;/textarea&gt;
+
+&lt;div class="playable-buttons"&gt;
+ &lt;input id="reset" type="button" value="Reset"&gt;
+ &lt;input id="solution" type="button" value="Show solution"&gt;
+&lt;/div&gt;
+</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">var textarea = document.getElementById('code');
+var reset = document.getElementById('reset');
+var solution = document.getElementById('solution');
+var code = textarea.value;
+var 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();
+});
+
+var jsSolution = 'var select = document.querySelector(\'select\');\nvar html = document.querySelector(\'.output\');\n\nselect.onchange = function() {\n var choice = select.value;\n\n switch(choice) {\n case \'black\':\n update(\'black\',\'white\');\n break;\n case \'white\':\n update(\'white\',\'black\');\n break;\n case \'purple\':\n update(\'purple\',\'white\');\n break;\n case \'yellow\':\n update(\'yellow\',\'darkgray\');\n break;\n case \'psychedelic\':\n update(\'lime\',\'purple\');\n break;\n }\n}\n\nfunction update(bgColor, textColor) {\n html.style.backgroundColor = bgColor;\n html.style.color = textColor;\n}';
+var 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) {
+ var scrollPos = textarea.scrollTop;
+ var caretPos = textarea.selectionStart;
+
+ var front = (textarea.value).substring(0, caretPos);
+ var 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%', 950, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<h2 id="Conclusion">Conclusion</h2>
+
+<p>And that's all you really need to know about conditional structures in JavaScript right now! I'm sure you'll have understood these concepts and worked through the examples with ease; if there is anything you didn't understand, feel free to read through the article again, or <a href="/en-US/Learn#Contact_us">contact us</a> to ask for help.</p>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li><a href="/en-US/Learn/JavaScript/First_steps/Math#Comparison_operators">Comparison operators</a></li>
+ <li><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Conditional_statements">Conditional statements in detail</a></li>
+ <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else">if...else reference</a></li>
+ <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">Conditional (ternary) operator reference</a></li>
+</ul>
+
+<p>{{NextMenu("Learn/JavaScript/Building_blocks/Looping_code", "Learn/JavaScript/Building_blocks")}}</p>
+
+<h2 id="In_this_module">In this module</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals">Making decisions in your code — conditionals</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code">Looping code</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">Functions — reusable blocks of code</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Build_your_own_function">Build your own function</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Return_values">Function return values</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events">Introduction to events</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Image_gallery">Image gallery</a></li>
+</ul>
diff --git a/files/zh-tw/learn/javascript/building_blocks/functions/index.html b/files/zh-tw/learn/javascript/building_blocks/functions/index.html
new file mode 100644
index 0000000000..719180656f
--- /dev/null
+++ b/files/zh-tw/learn/javascript/building_blocks/functions/index.html
@@ -0,0 +1,396 @@
+---
+title: 函數 - 可重複使用的代碼塊
+slug: Learn/JavaScript/Building_blocks/Functions
+translation_of: Learn/JavaScript/Building_blocks/Functions
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Looping_code","Learn/JavaScript/Building_blocks/Build_your_own_function", "Learn/JavaScript/Building_blocks")}}</div>
+
+<p class="summary">編碼中的另一個基本概念是函數,它允許您存儲一段代碼,該代碼在定義的塊內執行單個任務,然後在需要時使用一個簡短命令調用該代碼 - 而不必輸入相同的代碼 代碼多次。 在本文中,我們將探索函數背後的基本概念,例如基本語法,如何調用和定義它們,範圍和參數。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">Prerequisites:</th>
+ <td>Basic computer literacy, a basic understanding of HTML and CSS, <a href="/en-US/docs/Learn/JavaScript/First_steps">JavaScript first steps</a>.</td>
+ </tr>
+ <tr>
+ <th scope="row">Objective:</th>
+ <td>To understand the fundamental concepts behind JavaScript functions.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Where_do_I_find_functions">Where do I find functions?</h2>
+
+<p>In JavaScript, you'll find functions everywhere. In fact, we've been using functions all the way through the course so far; we've just not been talking about them very much. Now is the time, however, for us to start talking about functions explicitly, and really exploring their syntax.</p>
+
+<p>Pretty much anytime you make use of a JavaScript structure that features a pair of parentheses — <code>()</code> — and you're <strong>not</strong> using a common built-in language structure like a <a href="/en-US/Learn/JavaScript/Building_blocks/Looping_code#The_standard_for_loop">for loop</a>, <a href="/en-US/Learn/JavaScript/Building_blocks/Looping_code#while_and_do_..._while">while or do...while loop</a>, or <a href="/en-US/Learn/JavaScript/Building_blocks/conditionals#if_..._else_statements">if...else statement</a>, you are making use of a function.</p>
+
+<h2 id="Built-in_browser_functions">Built-in browser functions</h2>
+
+<p>We've made use of functions built in to the browser a lot in this course. Every time we manipulated a text string, for example:</p>
+
+<pre class="brush: js">var myText = 'I am a string';
+var newString = myText.replace('string', 'sausage');
+console.log(newString);
+// the replace() string function takes a string,
+// replaces one substring with another, and returns
+// a new string with the replacement made</pre>
+
+<p>Or every time we manipulated an array:</p>
+
+<pre class="brush: js">var myArray = ['I', 'love', 'chocolate', 'frogs'];
+var madeAString = myArray.join(' ');
+console.log(madeAString);
+// the join() function takes an array, joins
+// all the array items together into a single
+// string, and returns this new string</pre>
+
+<p>Or every time we generated a random number:</p>
+
+<pre class="brush: js">var myNumber = Math.random();
+// the random() function generates a random
+// number between 0 and 1, and returns that
+// number</pre>
+
+<p>...we were using a function!</p>
+
+<div class="note">
+<p><strong>Note</strong>: Feel free to enter these lines into your browser's JavaScript console to re-familiarize yourself with their functionality, if needed.</p>
+</div>
+
+<p>The JavaScript language has many built-in functions to allow you to do useful things without having to write all that code yourself. In fact, some of the code you are calling when you <strong>invoke</strong> (a fancy word for run, or execute) a built in browser function couldn't be written in JavaScript — many of these functions are calling parts of the background browser code, which is written largely in low-level system languages like C++, not web languages like JavaScript.</p>
+
+<p>Bear in mind that some built-in browser functions are not part of the core JavaScript language — some are defined as part of browser APIs, which build on top of the default language to provide even more functionality (refer to <a href="/en-US/Learn/JavaScript/First_steps/What_is_JavaScript#So_what_can_it_really_do">this early section of our course</a> for more descriptions). We'll look at using browser APIs in more detail in a later module.</p>
+
+<h2 id="Functions_versus_methods">Functions versus methods</h2>
+
+<p>One thing we need to clear up before we move on — technically speaking, built in browser functions are not functions — they are <strong>methods</strong>. This sounds a bit scary and confusing, but don't worry — the words function and method are largely interchangeable, at least for our purposes, at this stage in your learning.</p>
+
+<p>The distinction is that methods are functions defined inside objects. Built-in browser functions (methods) and variables (which are called <strong>properties</strong>) are stored inside structured objects, to make the code more efficient and easier to handle.</p>
+
+<p>You don't need to learn about the inner workings of structured JavaScript objects yet — you can wait until our later module that will teach you all about the inner workings of objects, and how to create your own. For now, we just wanted to clear up any possible confusion of method versus function — you are likely to meet both terms as you look at the available related resources across the Web.</p>
+
+<h2 id="Custom_functions">Custom functions</h2>
+
+<p>You've also seen a lot of <strong>custom functions</strong> in the course so far — functions defined in your code, not inside the browser. Anytime you saw a custom name with parentheses straight after it, you were using a custom function. In our <a href="http://mdn.github.io/learning-area/javascript/building-blocks/loops/random-canvas-circles.html">random-canvas-circles.html</a> example (see also the full <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/random-canvas-circles.html">source code</a>) from our <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code">loops article</a>, we included a custom <code>draw()</code> function that looked like this:</p>
+
+<pre class="brush: js">function draw() {
+ ctx.clearRect(0,0,WIDTH,HEIGHT);
+ for (var i = 0; i &lt; 100; i++) {
+ ctx.beginPath();
+ ctx.fillStyle = 'rgba(255,0,0,0.5)';
+ ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+ ctx.fill();
+ }
+}</pre>
+
+<p>This function draws 100 random circles inside an {{htmlelement("canvas")}} element. Every time we want to do that, we can just invoke the function with this</p>
+
+<pre class="brush: js">draw();</pre>
+
+<p>rather than having to write all that code out again every time we want to repeat it. And functions can contain whatever code you like — you can even call other functions from inside functions. The above function for example calls the <code>random()</code> function three times, which is defined by the following code:</p>
+
+<pre class="brush: js">function random(number) {
+ return Math.floor(Math.random()*number);
+}</pre>
+
+<p>We needed this function because the browser's built-in <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random">Math.random()</a> function only generates a random decimal number between 0 and 1. We wanted a random whole number between 0 and a specified number.</p>
+
+<h2 id="Invoking_functions">Invoking functions</h2>
+
+<p>You are probably clear on this by now, but just in case ... to actually use a function after it has been defined, you've got to run — or invoke — it. This is done by including the name of the function in the code somewhere, followed by parentheses.</p>
+
+<pre class="brush: js">function myFunction() {
+ alert('hello');
+}
+
+myFunction()
+// calls the function once</pre>
+
+<h2 id="Anonymous_functions">Anonymous functions</h2>
+
+<p>You may see functions defined and invoked in slightly different ways. So far we have just created a function like so:</p>
+
+<pre class="brush: js">function myFunction() {
+ alert('hello');
+}</pre>
+
+<p>But you can also create a function that doesn't have a name:</p>
+
+<pre class="brush: js">function() {
+ alert('hello');
+}</pre>
+
+<p>This is called an <strong>anonymous function</strong> — it has no name! It also won't do anything on its own. You generally use an anonymous function along with an event handler, for example the following would run the code inside the function whenever the associated button is clicked:</p>
+
+<pre class="brush: js">var myButton = document.querySelector('button');
+
+myButton.onclick = function() {
+ alert('hello');
+}</pre>
+
+<p>The above example would require there to be a {{htmlelement("button")}} element available on the page to select and click. You've already seen this structure a few times throughout the course, and you'll learn more about and see it in use in the next article.</p>
+
+<p>You can also assign an anonymous function to be the value of a variable, for example:</p>
+
+<pre class="brush: js">var myGreeting = function() {
+ alert('hello');
+}</pre>
+
+<p>This function could now be invoked using:</p>
+
+<pre class="brush: js">myGreeting();</pre>
+
+<p>This effectively gives the function a name; you can also assign the function to be the value of multiple variables, for example:</p>
+
+<pre class="brush: js">var anotherGreeting = function() {
+ alert('hello');
+}</pre>
+
+<p>This function could now be invoked using either of</p>
+
+<pre class="brush: js">myGreeting();
+anotherGreeting();</pre>
+
+<p>But this would just be confusing, so don't do it! When creating functions, it is better to just stick to this form:</p>
+
+<pre class="brush: js">function myGreeting() {
+ alert('hello');
+}</pre>
+
+<p>You will mainly use anonymous functions to just run a load of code in response to an event firing — like a button being clicked — using an event handler. Again, this looks something like this:</p>
+
+<pre class="brush: js">myButton.onclick = function() {
+ alert('hello');
+ // I can put as much code
+ // inside here as I want
+}</pre>
+
+<h2 id="Function_parameters">Function parameters</h2>
+
+<p>Some functions require <strong>parameters</strong> to be specified when you are invoking them — these are values that need to be included inside the function parentheses, which it needs to do its job properly.</p>
+
+<div class="note">
+<p><strong>Note</strong>: Parameters are sometimes called arguments, properties, or even attributes.</p>
+</div>
+
+<p>As an example, the browser's built-in <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random">Math.random()</a> function doesn't require any parameters. When called, it always returns a random number between 0 and 1:</p>
+
+<pre class="brush: js">var myNumber = Math.random();</pre>
+
+<p>The browser's built-in string <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace">replace()</a> function however needs two parameters — the substring to find in the main string, and the substring to replace that string with:</p>
+
+<pre class="brush: js">var myText = 'I am a string';
+var newString = myText.replace('string', 'sausage');</pre>
+
+<div class="note">
+<p><strong>Note</strong>: When you need to specify multiple parameters, they are separated by commas.</p>
+</div>
+
+<p>It should also be noted that sometimes parameters are optional — you don't have to specify them. If you don't, the function will generally adopt some kind of default behavior. As an example, the array <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join">join()</a> function's parameter is optional:</p>
+
+<pre class="brush: js">var myArray = ['I', 'love', 'chocolate', 'frogs'];
+var madeAString = myArray.join(' ');
+// returns 'I love chocolate frogs'
+var madeAString = myArray.join();
+// returns 'I,love,chocolate,frogs'</pre>
+
+<p>If no parameter is included to specify a joining/delimiting character, a comma is used by default.</p>
+
+<h2 id="Function_scope_and_conflicts">Function scope and conflicts</h2>
+
+<p>Let's talk a bit about {{glossary("scope")}} — a very important concept when dealing with functions. When you create a function, the variables and other things defined inside the function are inside their own separate <strong>scope</strong>, meaning that they are locked away in their own separate compartments, unreachable from inside other functions or from code outside the functions.</p>
+
+<p>The top level outside all your functions is called the <strong>global scope</strong>. Values defined in the global scope are accessible from everywhere in the code.</p>
+
+<p>JavaScript is set up like this for various reasons — but mainly because of security and organization. Sometimes you don't want variables to be accessible from everywhere in the code — external scripts that you call in from elsewhere could start to mess with your code and cause problems because they happen to be using the same variable names as other parts of the code, causing conflicts. This might be done maliciously, or just by accident.</p>
+
+<p>For example, say you have an HTML file that is calling in two external JavaScript files, and both of them have a variable and a function defined that use the same name:</p>
+
+<pre class="brush: html">&lt;!-- Excerpt from my HTML --&gt;
+&lt;script src="first.js"&gt;&lt;/script&gt;
+&lt;script src="second.js"&gt;&lt;/script&gt;
+&lt;script&gt;
+ greeting();
+&lt;/script&gt;</pre>
+
+<pre class="brush: js">// first.js
+var name = 'Chris';
+function greeting() {
+ alert('Hello ' + name + ': welcome to our company.');
+}</pre>
+
+<pre class="brush: js">// second.js
+var name = 'Zaptec';
+function greeting() {
+ alert('Our company is called ' + name + '.');
+}</pre>
+
+<p>Both functions you want to call are called <code>greeting()</code>, but you can only ever access the <code>second.js</code> file's <code>greeting()</code> function — it is applied to the HTML later on in the source code, so its variable and function overwrite the ones in <code>first.js</code>.</p>
+
+<div class="note">
+<p><strong>Note</strong>: You can see this example <a href="http://mdn.github.io/learning-area/javascript/building-blocks/functions/conflict.html">running live on GitHub</a> (see also the <a href="https://github.com/mdn/learning-area/tree/master/javascript/building-blocks/functions">source code</a>).</p>
+</div>
+
+<p>Keeping parts of your code locked away in functions avoids such problems, and is considered best practice.</p>
+
+<p>It is a bit like a zoo. The lions, zebras, tigers, and penguins are kept in their own enclosures, and only have access to the things inside their enclosures — in the same manner as the function scopes. If they were able to get into other enclosures, problems would occur. At best, different animals would feel really uncomfortable inside unfamiliar habitats — a lion or tiger would feel terrible inside the penguins' watery, icy domain. At worst, the lions and tigers might try to eat the penguins!</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/14079/MDN-mozilla-zoo.png" style="display: block; margin: 0 auto;"></p>
+
+<p>The zoo keeper is like the global scope — he or she has the keys to access every enclosure, to restock food, tend to sick animals, etc.</p>
+
+<h3 id="Active_learning_Playing_with_scope">Active learning: Playing with scope</h3>
+
+<p>Let's look at a real example to demonstrate scoping.</p>
+
+<ol>
+ <li>First, make a local copy of our <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/functions/function-scope.html">function-scope.html</a> example. This contains two functions called <code>a()</code> and <code>b()</code>, and three variables — <code>x</code>, <code>y</code>, and <code>z</code> — two of which are defined inside the functions, and one in the global scope. It also contains a third function called <code>output()</code>, which takes a single parameter and outputs it in a paragraph on the page.</li>
+ <li>Open the example up in a browser and in your text editor.</li>
+ <li>Open the JavaScript console in your browser developer tools. In the JavaScript console, enter the following command:
+ <pre class="brush: js">output(x);</pre>
+ You should see the value of variable <code>x</code> output to the screen.</li>
+ <li>Now try entering the following in your console
+ <pre class="brush: js">output(y);
+output(z);</pre>
+ Both of these should return an error along the lines of "<a href="/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined">ReferenceError: y is not defined</a>". Why is that? Because of function scope — <code>y</code> and <code>z</code> are locked inside the <code>a()</code> and <code>b()</code> functions, so <code>output()</code> can't access them when called from the global scope.</li>
+ <li>However, what about when it's called from inside another function? Try editing <code>a()</code> and <code>b()</code> so they look like this:
+ <pre class="brush: js">function a() {
+ var y = 2;
+ output(y);
+}
+
+function b() {
+ var z = 3;
+ output(z);
+}</pre>
+ Save the code and reload it in your browser, then try calling the <code>a()</code> and <code>b()</code> functions from the JavaScript console:
+
+ <pre class="brush: js">a();
+b();</pre>
+ You should see the <code>y</code> and <code>z</code> values output in the page. This works fine, as the <code>output()</code> function is being called inside the other functions — in the same scope as the variables it is printing are defined in, in each case. <code>output()</code> itself is available from anywhere, as it is defined in the global scope.</li>
+ <li>Now try updating your code like this:
+ <pre class="brush: js">function a() {
+ var y = 2;
+ output(x);
+}
+
+function b() {
+ var z = 3;
+ output(x);
+}</pre>
+ Save and reload again, and try this again in your JavaScript console:
+
+ <pre class="brush: js">a();
+b();</pre>
+ Both the <code>a()</code> and <code>b()</code> call should output the value of x — 1. These work fine because even though the <code>output()</code> calls are not in the same scope as <code>x</code> is defined in, <code>x</code> is a global variable so is available inside all code, everywhere.</li>
+ <li>Finally, try updating your code like this:
+ <pre class="brush: js">function a() {
+ var y = 2;
+ output(z);
+}
+
+function b() {
+ var z = 3;
+ output(y);
+}</pre>
+ Save and reload again, and try this again in your JavaScript console:
+
+ <pre class="brush: js">a();
+b();</pre>
+ This time the <code>a()</code> and <code>b()</code> calls will both return that annoying "<a href="/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined">ReferenceError: z is not defined</a>" error — this is because the <code>output()</code> calls and the variables they are trying to print are not defined inside the same function scopes — the variables are effectively invisible to those function calls.</li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: The same scoping rules do not apply to loop (e.g. <code>for() { ... }</code>) and conditional blocks (e.g. <code>if() { ... }</code>) — they look very similar, but they are not the same thing! Take care not to get these confused.</p>
+</div>
+
+<div class="note">
+<p><strong>Note</strong>: The <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined">ReferenceError: "x" is not defined</a> error is one of the most common you'll encounter. If you get this error and you are sure that you have defined the variable in question, check what scope it is in.</p>
+</div>
+
+<ul>
+</ul>
+
+<h3 id="Functions_inside_functions">Functions inside functions</h3>
+
+<p>Keep in mind that you can call a function from anywhere, even inside another function.  This is often used as a way to keep code tidy — if you have a big complex function, it is easier to understand if you break it down into several sub-functions:</p>
+
+<pre class="brush: js">function myBigFunction() {
+ var myValue;
+
+ subFunction1();
+ subFunction2();
+ subFunction3();
+}
+
+function subFunction1() {
+ console.log(myValue);
+}
+
+function subFunction2() {
+ console.log(myValue);
+}
+
+function subFunction3() {
+ console.log(myValue);
+}
+</pre>
+
+<p>Just make sure that the values being used inside the function are properly in scope. The example above would throw an error <code>ReferenceError: myValue is not defined</code>, because although the <code>myValue</code> variable is defined in the same scope as the function calls, it is not defined inside the function definitions — the actual code that is run when the functions are called. To make this work, you'd have to pass the value into the function as a parameter, like this:</p>
+
+<pre class="brush: js">function myBigFunction() {
+ var myValue = 1;
+
+ subFunction1(myValue);
+ subFunction2(myValue);
+ subFunction3(myValue);
+}
+
+function subFunction1(value) {
+ console.log(value);
+}
+
+function subFunction2(value) {
+ console.log(value);
+}
+
+function subFunction3(value) {
+ console.log(value);
+}</pre>
+
+<h2 id="Conclusion">Conclusion</h2>
+
+<p>This article has explored the fundamental concepts behind functions, paving the way for the next one in which we get practical and take you through the steps to building up your own custom function.</p>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Functions detailed guide</a> — covers some advanced features not included here.</li>
+ <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions reference</a></li>
+ <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">Default parameters</a>, <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a> — advanced concept references</li>
+</ul>
+
+<ul>
+</ul>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Looping_code","Learn/JavaScript/Building_blocks/Build_your_own_function", "Learn/JavaScript/Building_blocks")}}</p>
+
+<p> </p>
+
+<h2 id="In_this_module">In this module</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals">Making decisions in your code — conditionals</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code">Looping code</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">Functions — reusable blocks of code</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Build_your_own_function">Build your own function</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Return_values">Function return values</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events">Introduction to events</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Image_gallery">Image gallery</a></li>
+</ul>
+
+<p> </p>
diff --git a/files/zh-tw/learn/javascript/building_blocks/image_gallery/index.html b/files/zh-tw/learn/javascript/building_blocks/image_gallery/index.html
new file mode 100644
index 0000000000..32c5a1867a
--- /dev/null
+++ b/files/zh-tw/learn/javascript/building_blocks/image_gallery/index.html
@@ -0,0 +1,135 @@
+---
+title: 影像圖庫
+slug: Learn/JavaScript/Building_blocks/Image_gallery
+tags:
+ - JavaScript
+ - 事件
+ - 事件處理器
+ - 優先國際化
+ - 初學者
+ - 學習
+ - 條件式
+ - 編碼腳本
+ - 評量
+ - 迴圈
+translation_of: Learn/JavaScript/Building_blocks/Image_gallery
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenu("Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}</div>
+
+<p class="summary">現在我們已經看過了基本的JavaScript組建,我們將讓你做一個測試,從建立一個在很多網站上常見的事物 — JavaScript基礎的影像圖庫,來測試你對迴圈、函數、條件式及事件的知識。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">先修課程:</th>
+ <td>在進行這個評量前,你應已閱讀、練習了本模組中所有的文章。</td>
+ </tr>
+ <tr>
+ <th scope="row">目的:</th>
+ <td>測試對JavaScript中迴圈、函數、條件式及事件的瞭解程度。</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="從這裡開始">從這裡開始</h2>
+
+<p>要進行這個評量,你要先下載 <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/gallery/gallery-start.zip?raw=true">grab the ZIP</a> 檔案,解壓縮在你電腦中的某個檔案夾作為範例。</p>
+
+<div class="note">
+<p><strong>提醒:</strong>你也可以在某些網站進行評鑑,如 <a class="external external-icon" href="http://jsbin.com/">JSBin</a> 或<a class="external external-icon" href="https://thimble.mozilla.org/">Thimble</a>。你可以把這些HTML、CSS和JavaScript貼到這些線上編輯器中。如果你用了一個沒法把JavaScript/CSS分別放在不同面板的線上編輯器,你可以放心的把這些<code>&lt;script&gt;</code>/<code>&lt;style&gt;</code>元件改成inline貼進HTML網頁裡。</p>
+</div>
+
+<h2 id="專案簡報">專案簡報</h2>
+
+<p>你手上已有我們提供的一些 HTML、CSS 和圖片資料,以及幾行 JavaScript 程式碼;你要寫一些必要的 JavaScript 讓它變成可運作的程式。這些 HTML 的 body 看起來如下:</p>
+
+<pre class="brush: html">&lt;h1&gt;Image gallery example&lt;/h1&gt;
+
+&lt;div class="full-img"&gt;
+ &lt;img class="displayed-img" src="images/pic1.jpg"&gt;
+ &lt;div class="overlay"&gt;&lt;/div&gt;
+ &lt;button class="dark"&gt;Darken&lt;/button&gt;
+&lt;/div&gt;
+
+&lt;div class="thumb-bar"&gt;
+
+&lt;/div&gt;</pre>
+
+<p>完成後看起來像下圖:</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13787/gallery.png" style="display: block; margin: 0 auto;"></p>
+
+<ul>
+</ul>
+
+<p>範例 CSS 檔案中最有趣的部分是:</p>
+
+<ul>
+ <li>在 <code>full-img &lt;div&gt;</code> 裡有的三個組成元素使用絕對位置 —  <code>&lt;img&gt;</code> 展示全尺寸圖片,在它正上方有個與它尺寸相同的空 <code>&lt;div&gt;</code> (用來放置用半透明的背景色彩讓圖片產生變暗效果的層),然後 <code>&lt;button&gt;</code> 用來控制變暗效果。</li>
+ <li>設定 <code>thumb-bar &lt;div&gt;</code> (一般叫做「縮圖」的圖片)裡的圖片讓它縮小成原來的20%,之後讓它浮(float)在左邊讓縮圖能一個個相鄰的排成一列。</li>
+</ul>
+
+<p>在你的 JavaScript 裡需要:</p>
+
+<ul>
+ <li>讓所有圖片迴圈(Loop) through all the images, 在 <code>thumb-bar &lt;div&gt;</code> 裡的每個 <code>&lt;img&gt;</code> 塞進一個 <code>&lt;img&gt;</code> ,讓圖片內嵌在頁面上。</li>
+ <li>在 <code>thumb-bar &lt;div&gt;</code> 裡的每個 <code>&lt;img&gt;</code> 添加一個  <code>onclick</code> 處理器使這個圖片被點擊時會放大展示在 <code>displayed-img &lt;img&gt;</code> 裡。</li>
+ <li>在 <code>&lt;button&gt;</code> 添加一個  <code>onclick</code> 處理器,當點擊時,全尺寸圖片產生暗化效果,再次點擊時移除暗化效果。</li>
+</ul>
+
+<p>為了讓你更清楚,你可以看看這個 <a href="http://mdn.github.io/learning-area/javascript/building-blocks/gallery/">完成的範例</a> (但別偷看原始碼!)</p>
+
+<h2 id="一步步完成">一步步完成</h2>
+
+<p>接下來幾節描述你該怎麼做。</p>
+
+<h3 id="讓所有圖片迴圈">讓所有圖片迴圈</h3>
+
+<p>我們已提供了幾行程式碼:將<code>thumb-bar</code>和 <code>&lt;div&gt;</code>儲存在 <code>thumbBar</code>這個變數裡、建立一個新的 <code>&lt;img&gt;</code> 元件、將它的 <code>src</code> 屬性設定在一個值為 <code>xxx</code> 的佔位符中,以及在 <code>thumbBar</code> 裡增加新 <code>&lt;img&gt;</code> 。</p>
+
+<p>你要做的是:</p>
+
+<ol>
+ <li>Put the section of code below the "Looping through images" comment inside a loop that loops through all 5 images — you just need to loop through five numbers, one representing each image.</li>
+ <li>In each loop iteration, replace the <code>xxx</code> placeholder value with a string that will equal the path to the image in each case. We are setting the value of the <code>src</code> attribute to this value in each case. Bear in mind that in each case, the image is inside the images directory and its name is <code>pic1.jpg</code>, <code>pic2.jpg</code>, etc.</li>
+</ol>
+
+<h3 id="在每個縮圖上添加onclick事件處理器">在每個縮圖上添加onclick事件處理器</h3>
+
+<p>In each loop iteration, you need to add an <code>onclick</code> handler to the current <code>newImage</code> — this should:</p>
+
+<ol>
+ <li>在每個 <code>&lt;img&gt;</code> 中把<code>"src"</code>作為運行<code>getAttribute()</code> 函數的參數,取得現在這張圖片的 <code>src</code> 屬性的值。但是要怎麼抓到現在這張圖片?如果用<code>newImage</code> 是做不到的,當在添加事件處理器前,迴圈已經先完成了;所以你每次都獲得前一個 <code>&lt;img&gt;</code>的回傳的 <code>src</code> 值。解法是,記住,在每個事件中,事件處理器的目標是 <code>&lt;img&gt;</code> ,如何獲得事件物件的資訊呢?</li>
+ <li>Run a function, passing it the returned <code>src</code> value as a parameter. You can call this function whatever you like.</li>
+ <li>This event handler function should set the <code>src</code> attribute value of the <code>displayed-img &lt;img&gt;</code> to the <code>src</code> value passed in as a parameter. We've already provided you with a line that stores a reference to the relevant <code>&lt;img&gt;</code> in a variable called <code>displayedImg</code>. Note that we want a defined named function here.</li>
+</ol>
+
+<h3 id="寫一個讓暗化亮化按鈕可以運作的處理器">寫一個讓暗化/亮化按鈕可以運作的處理器</h3>
+
+<p>That just leaves our darken/lighten <code>&lt;button&gt;</code> — we've already provided a line that stores a reference to the <code>&lt;button&gt;</code> in a variable called <code>btn</code>. You need to add an <code>onclick</code> handler that:</p>
+
+<ol>
+ <li>Checks the current class name set on the <code>&lt;button&gt;</code> — you can again achieve this by using <code>getAttribute()</code>.</li>
+ <li>If the class name is <code>"dark"</code>, changes the <code>&lt;button&gt;</code> class to <code>"light"</code> (using <code><a href="/en-US/docs/Web/API/Element/setAttribute">setAttribute()</a></code>), its text content to "Lighten", and the {{cssxref("background-color")}} of the overlay <code>&lt;div&gt;</code> to <code>"rgba(0,0,0,0.5)"</code>.</li>
+ <li>If the class name not <code>"dark"</code>, changes the <code>&lt;button&gt;</code> class to <code>"dark"</code>, its text content back to "Darken", and the {{cssxref("background-color")}} of the overlay <code>&lt;div&gt;</code> to <code>"rgba(0,0,0,0)"</code>.</li>
+</ol>
+
+<p>The following lines provide a basis for achieving the changes stipulated in points 2 and 3 above.</p>
+
+<pre class="brush: js">btn.setAttribute('class', xxx);
+btn.textContent = xxx;
+overlay.style.backgroundColor = xxx;</pre>
+
+<h2 id="提醒與提示">提醒與提示</h2>
+
+<ul>
+ <li>你完全不需要去編輯任何的HTML或CSS。</li>
+</ul>
+
+<h2 id="評量">評量</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-community.org/t/learning-web-development-marking-guides-and-questions/16294">Learning Area Discourse thread</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/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}</p>
diff --git a/files/zh-tw/learn/javascript/building_blocks/index.html b/files/zh-tw/learn/javascript/building_blocks/index.html
new file mode 100644
index 0000000000..500b7d28ed
--- /dev/null
+++ b/files/zh-tw/learn/javascript/building_blocks/index.html
@@ -0,0 +1,52 @@
+---
+title: JavaScript building blocks
+slug: Learn/JavaScript/Building_blocks
+tags:
+ - JavaScript
+ - TopicStub
+ - 事件
+ - 入門者
+ - 函式
+ - 指南
+ - 模組
+ - 評量
+ - 迴圈
+translation_of: Learn/JavaScript/Building_blocks
+---
+<div>{{LearnSidebar}}</div>
+
+<p class="summary">在本單元中,我們繼續介紹所有JavaScript的關鍵基本功能,將注意力轉向常見的代碼塊類型,如條件語句,循環,函數和事件。 你已經在課程中看到了這些東西,但只是順便說一下 - 在這裡我們將明確地討論它。</p>
+
+<h2 id="先決條件">先決條件</h2>
+
+<p>開始這個模組之前,你應該已經熟悉 <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">HTML</a> 和 <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS">CSS</a> 的基礎知識了,你也應該閱讀完前一個模組 - <a href="/en-US/docs/Learn/JavaScript/First_steps">JavaScript 入門</a> - 的內容了。</p>
+
+<div class="note">
+<p><strong>注意</strong>: 假如你正使用平板、電腦或任何無法讓你可以建立檔案的裝置時,你可以試著透過線上程式碼工具 (像是 <a href="http://jsbin.com/">JSBin</a> 或 <a href="https://thimble.mozilla.org/">Thimble</a>) 測試文章的測試碼。</p>
+</div>
+
+<h2 id="指南">指南</h2>
+
+<dl>
+ <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/Building_blocks/%E6%A2%9D%E4%BB%B6">在代碼中做出決定 - 條件</a></dt>
+ <dd>在任何編程語言中,代碼都需要根據不同的輸入做出決策並相應地執行操作。 例如,在遊戲中,如果玩家的生命數量為0,則遊戲結束。 在天氣應用程序中,如果在早上查看,則顯示日出圖形; 如果是夜晚,則顯示星星和月亮。 在本文中,我們將探討條件結構如何在JavaScript中工作。</dd>
+ <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/Building_blocks/Looping_code" rel="nofollow">程式碼迴圈</a></dt>
+ <dd>有時候你需要超過一行的程式碼完成一項任務,舉例來說:尋找一個擁有許多名字的清單。透過編輯程式,迴圈可以幫助你完美的完成這項工作,在本文中,我們將探討迴圈的結構如何在 JavaScript 中運作。</dd>
+ <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/Building_blocks/Functions" rel="nofollow">函式 — 可重複使用的程式碼區塊</a></dt>
+ <dd>撰寫程式的另一個基本概念是函式 (function),它允許你在一個定義好的區塊內,存放一些程式碼。定義好的函式後,無論你需要在一個單一簡短的指令列用到它,或者是重複使用相同的片段程式碼,你都可以不段重複地呼叫這些函式執行對應的內容。在本文中,我們將探索函式的基本概念,像是基本語法、如何定義函式內容、以及函式將會使用的參數。</dd>
+ <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/Building_blocks/Build_your_own_function" rel="nofollow">建立自己的函式</a></dt>
+ <dd>前面許多文章已經提到大部分的基本理論基礎了,在本文中,我們將分享一個實際的經驗,你將學習到關於打造自定義函式的實務範例。透過這樣的學習方式,我們也進一步解釋一些函式相關的細節知識。</dd>
+ <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/Building_blocks/Return_values" rel="nofollow">函式回傳值</a></dt>
+ <dd>這堂課程中最後一個想要說明的基本概念就是函式的回傳值,一些函式執行完畢後,不會回傳一個數值;但有些函式則會。理解這些函式的回傳值是重要的概念,本文中,你將學會如何在自定義的函式中,回傳有用的數值提供給其他函式使用。</dd>
+ <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/Building_blocks/Events" rel="nofollow">事件介紹</a></dt>
+ <dd>事件代表你所撰寫的程式在一套系統內所產生的動作或發生的事情,舉例來說:假如一位使用者在網頁點擊一個按鈕時,你可能想要讓使用者點擊該按鈕後,在畫面呈現一個訊息方塊。在本課程最後一篇文章內,我們將討論一些與事件相關的重要概念、以及這些事件在瀏覽器中,如何呈現給使用者。</dd>
+</dl>
+
+<h2 id="評量">評量</h2>
+
+<p>下方的試題將會測驗你對於上述幾項概念的 JavaScript 基本知識。</p>
+
+<dl>
+ <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/Building_blocks/Image_gallery">圖庫</a></dt>
+ <dd>我們已經看過許多 JavaScript 的基礎程式碼,我們將測驗你關於迴圈、函式、條件式迴圈與事件等相關的知識,測驗的方式是透過建立一個由 JavaScript 打造而成的圖庫應用程式。</dd>
+</dl>
diff --git a/files/zh-tw/learn/javascript/building_blocks/looping_code/index.html b/files/zh-tw/learn/javascript/building_blocks/looping_code/index.html
new file mode 100644
index 0000000000..0e1e400b4d
--- /dev/null
+++ b/files/zh-tw/learn/javascript/building_blocks/looping_code/index.html
@@ -0,0 +1,928 @@
+---
+title: 循環代碼
+slug: Learn/JavaScript/Building_blocks/Looping_code
+translation_of: Learn/JavaScript/Building_blocks/Looping_code
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/Building_blocks/conditionals","Learn/JavaScript/Building_blocks/Functions", "Learn/JavaScript/Building_blocks")}}</div>
+
+<p class="summary">編程語言對於快速完成重複性任務非常有用,從多個基本計算到幾乎任何其他需要完成大量類似工作的情況。 在這裡,我們將看看JavaScript中可用於處理此類需求的循環結構。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">Prerequisites:</th>
+ <td>Basic computer literacy, a basic understanding of HTML and CSS, <a href="/en-US/docs/Learn/JavaScript/First_steps">JavaScript first steps</a>.</td>
+ </tr>
+ <tr>
+ <th scope="row">Objective:</th>
+ <td>To understand how to use loops in JavaScript.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="保持循環">保持循環</h2>
+
+<p>循環,循環,循環。 除了與受歡迎的早餐穀物,過山車和音樂作品有關聯,它們還是編程中的關鍵概念。 編程循環都是一遍又一遍地做同一件事-在編程方面被稱為迭代。</p>
+
+<p>讓我們考慮一個農民的例子,他要確保他有足夠的食物來養家糊口。 他可能使用以下循環來實現此目的:</p>
+
+<p><br>
+ <img alt="" src="https://mdn.mozillademos.org/files/13755/loop_js-02-farm.png" style="display: block; margin: 0 auto;"></p>
+
+<p>循環通常具有以下一項或多項功能:</p>
+
+<ul>
+ <li> 一個用一定值初始化的計數器-這是循環的起點(上面的“開始:我沒有食物”)。</li>
+ <li>一種條件,它是對/錯測試,用於確定循環是繼續運行還是停止(通常在計數器達到某個值時)。 “我是否有足夠的食物?”對此進行了說明。 以上。 假設他需要10份食物來養家糊口的話。</li>
+ <li>一個迭代器,通常在每個連續循環上使計數器增加一小部分,直到條件不再成立為止。 上面我們沒有明確說明這一點,但是我們可以考慮一下農民每小時可以收集2份食物。 每小時之後,他收集的食物數量增加了2,然後他檢查是否有足夠的食物。 如果他已達到10個部分(此時條件不再成立,則循環退出),他可以停止收集並回家。</li>
+</ul>
+
+<p>In {{glossary("pseudocode")}}, this would look something like the following:</p>
+
+<pre class="notranslate">loop(food = 0; foodNeeded = 10) {
+ if (food = foodNeeded) {
+ exit loop;
+ // We have enough food; let's go home
+ } else {
+ food += 2; // Spend an hour collecting 2 more food
+ // loop will then run again
+ }
+}</pre>
+
+<p>因此,所需的食物數量設置為10,而農民當前擁有的食物數量設置為0。在循環的每次迭代中,我們檢查農民擁有的食物數量是否等於他所需的數量。 如果是這樣,我們可以退出循環。 如果不是這樣,農民將花一個小時收集兩份食物,然後循環再次運行。</p>
+
+<h3 id="不用麻煩">不用麻煩</h3>
+
+<p>在這一點上,您可能了解了循環背後的高級概念,但您可能在想:“好,很好,但這如何幫助我編寫更好的JavaScript代碼?” 如前所述,循環與一次又一次地執行同一操作有關,這對於快速完成重複性任務非常有用。</p>
+
+<p>通常,代碼在每次循環的每次迭代中都會略有不同,這意味著您可以完成全部相似但略有不同的任務,一般情況,如果您要執行許多不同的計算,則需要不斷地執行不同的式子,而不能一遍又一遍重複!</p>
+
+<p>讓我們看一個示例,以完美地說明為什麼循環是如此便利。 Let's say we wanted to draw 100 random circles on a {{htmlelement("canvas")}} element (press the <em>Update</em> button to run the example again and again to see different random sets):</p>
+
+<div class="hidden">
+<h6 id="Hidden_code">Hidden code</h6>
+
+<pre class="brush: html notranslate">&lt;!DOCTYPE html&gt;
+&lt;html&gt;
+ &lt;head&gt;
+ &lt;meta charset="utf-8"&gt;
+ &lt;title&gt;Random canvas circles&lt;/title&gt;
+ &lt;style&gt;
+ html {
+ width: 100%;
+ height: inherit;
+ background: #ddd;
+ }
+
+ canvas {
+ display: block;
+ }
+
+ body {
+ margin: 0;
+ }
+
+ button {
+ position: absolute;
+ top: 5px;
+ left: 5px;
+ }
+ &lt;/style&gt;
+ &lt;/head&gt;
+ &lt;body&gt;
+
+ &lt;button&gt;Update&lt;/button&gt;
+
+ &lt;canvas&gt;&lt;/canvas&gt;
+
+
+ &lt;script&gt;
+ var btn = document.querySelector('button');
+ var canvas = document.querySelector('canvas');
+ var ctx = canvas.getContext('2d');
+
+ var WIDTH = document.documentElement.clientWidth;
+ var HEIGHT = document.documentElement.clientHeight;
+
+ canvas.width = WIDTH;
+ canvas.height = HEIGHT;
+
+ function random(number) {
+ return Math.floor(Math.random()*number);
+ }
+
+ function draw() {
+ ctx.clearRect(0,0,WIDTH,HEIGHT);
+ for (var i = 0; i &lt; 100; i++) {
+ ctx.beginPath();
+ ctx.fillStyle = 'rgba(255,0,0,0.5)';
+ ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+ ctx.fill();
+ }
+ }
+
+ btn.addEventListener('click',draw);
+
+ &lt;/script&gt;
+
+ &lt;/body&gt;
+&lt;/html&gt;</pre>
+</div>
+
+<p>{{ EmbedLiveSample('Hidden_code', '100%', 400, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<p>您現在不必了解所有代碼,但讓我們看一下實際繪製100個圓圈的代碼部分:</p>
+
+<pre class="brush: js notranslate">for (var i = 0; i &lt; 100; i++) {
+ ctx.beginPath();
+ ctx.fillStyle = 'rgba(255,0,0,0.5)';
+ ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+ ctx.fill();
+}</pre>
+
+<ul>
+ <li><code>代碼前面定義的random(),返回0到x-1之間的整數。</code></li>
+ <li><code>WIDTH和HEIGHT是內部瀏覽器窗口的寬度和高度。</code></li>
+</ul>
+
+<p>您應該了解基本概念-我們正在使用一個循環來運行此代碼的100次迭代,每個迭代在頁面上的隨機位置繪製一個圓圈。 無論我們繪製100個圓,1000個還是10,000個,所需的代碼量都是相同的。 只需更改一個數字。</p>
+
+<p>如果我們不在此處使用循環,則必須為每個要繪製的圓重複以下代碼:</p>
+
+<pre class="brush: js notranslate">ctx.beginPath();
+ctx.fillStyle = 'rgba(255,0,0,0.5)';
+ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+ctx.fill();</pre>
+
+<p>這將變得很無聊,並且很難很快維護。 循環確實是最好的。</p>
+
+<h2 id="循環的規範">循環的規範</h2>
+
+<p>讓我們開始探索一些特定的循環結構。 第一個是for循環,您將在大多數時候使用它,它具有以下語法:</p>
+
+<pre class="notranslate">for (initializer; exit-condition; final-expression) {
+ // code to run
+}</pre>
+
+<p>這裡我們有:</p>
+
+<ol>
+ <li>關鍵字“ for”,即跟隨其後的一些括號。</li>
+ <li>在括號內,我們有三個項目,以 ; 分隔:
+ <ol>
+ <li>初始化程序-通常是一個設置為數字的變量,該變量將遞增以計算循環運行的次數。 有時也稱為計數器變量。</li>
+ <li>退出條件-如前所述,它定義了循環何時應停止循環。 通常,這是一個具有比較運算符的表達式,該測試用於檢驗是否滿足退出條件。</li>
+ <li>最終表達式—每當循環經過完整的迭代時,總是對它進行評估(或運行)。 它通常用於遞增(或在某些情況下遞減)計數器變量,以使其更接近退出條件值。</li>
+ </ol>
+ </li>
+ <li>一些花括號包含一個代碼塊-每次循環迭代時都將運行此代碼。</li>
+</ol>
+
+<p>讓我們看一個真實的例子,以便我們可以更清楚地看到它們的作用。</p>
+
+<pre class="brush: js notranslate">var cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin'];
+var info = 'My cats are called ';
+var para = document.querySelector('p');
+
+for (var i = 0; i &lt; cats.length; i++) {
+ info += cats[i] + ', ';
+}
+
+para.textContent = info;</pre>
+
+<p>這為我們提供了以下輸出:</p>
+
+<div class="hidden">
+<h6 id="Hidden_code_2">Hidden code 2</h6>
+
+<pre class="brush: html notranslate">&lt;!DOCTYPE html&gt;
+&lt;html&gt;
+ &lt;head&gt;
+ &lt;meta charset="utf-8"&gt;
+ &lt;title&gt;Basic for loop example&lt;/title&gt;
+ &lt;style&gt;
+
+ &lt;/style&gt;
+ &lt;/head&gt;
+ &lt;body&gt;
+
+ &lt;p&gt;&lt;/p&gt;
+
+
+ &lt;script&gt;
+ var cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin'];
+ var info = 'My cats are called ';
+ var para = document.querySelector('p');
+
+ for (var i = 0; i &lt; cats.length; i++) {
+ info += cats[i] + ', ';
+ }
+
+ para.textContent = info;
+
+ &lt;/script&gt;
+
+ &lt;/body&gt;
+&lt;/html&gt;</pre>
+</div>
+
+<p>{{ EmbedLiveSample('Hidden_code_2', '100%', 60, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<div class="note">
+<p><strong>Note</strong>: You can find this <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/basic-for.html">example code on GitHub</a> too (also <a href="http://mdn.github.io/learning-area/javascript/building-blocks/loops/basic-for.html">see it running live</a>).</p>
+</div>
+
+<p>這顯示了一個循環,該循環用於遍歷數組中的項目並對其進行處理-這是JavaScript中非常常見的模式。 這裡:</p>
+
+<ol>
+ <li>迭代器i從0開始(變量i = 0)。</li>
+ <li>它被告知運行,直到它不再小於cats數組的長度為止。 這很重要,退出條件顯示了循環仍將運行的條件。 因此,在這種情況下,儘管i &lt;cats.length仍然為true,循環仍將運行。</li>
+ <li>在循環內部,我們將當前循環項(cats [i]是cats [無論 i 當時是什麼])與一個逗號和一個空格連接到info變量的末尾。 所以:
+ <ol>
+ <li>在第一次運行中,i = 0,因此cats [0] +','將連接到info(“ Bill,”)上。</li>
+ <li>在第二次運行中,i = 1,因此cats [1] +','將連接到info(“ Jeff,”)上</li>
+ <li>等等。 每次循環運行後,將1加到i(i ++),然後該過程將再次開始。</li>
+ </ol>
+ </li>
+ <li>當 i 等於cats.length時,循環將停止,瀏覽器將繼續循環下方的下一段代碼。</li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: We have made the exit condition <code>i &lt; cats.length</code>, not <code>i &lt;= cats.length</code>, because computers count from 0, not 1 — we are starting <code>i</code> at <code>0</code>, and going up to <code>i = 4</code> (the index of the last array item). <code>cats.length</code> returns 5, as there are 5 items in the array, but we don't want to get up to <code>i = 5</code>, as that would return <code>undefined</code> for the last item (there is no array item with an index of 5). So therefore we want to go up to 1 less than <code>cats.length</code> (<code>i &lt;</code>), not the same as <code>cats.length</code> (<code>i &lt;=</code>).</p>
+</div>
+
+<div class="note">
+<p><strong>Note</strong>: A common mistake with exit conditions is making them use "equal to" (<code>===</code>) rather than say "less than or equal to" (<code>&lt;=</code>). If we wanted to run our loop up to <code>i = 5</code>, the exit condition would need to be <code>i &lt;= cats.length</code>. If we set it to <code>i === cats.length</code>, the loop would not run at all because <code>i</code> is not equal to <code>5</code> on the first loop iteration, so it would stop immediately.</p>
+</div>
+
+<p>我們剩下的一個小問題是最終輸出語句的格式不太正確:</p>
+
+<blockquote>
+<p>My cats are called Bill, Jeff, Pete, Biggles, Jasmin,</p>
+</blockquote>
+
+<p>理想情況下,我們希望在最終循環迭代中更改串聯,以使句子的末尾沒有逗號。 好吧,沒問題-我們可以很高興地在for循環中插入一個條件來處理這種特殊情況:</p>
+
+<pre class="brush: js notranslate">for (var i = 0; i &lt; cats.length; i++) {
+ if (i === cats.length - 1) {
+ info += 'and ' + cats[i] + '.';
+ } else {
+ info += cats[i] + ', ';
+ }
+}</pre>
+
+<div class="note">
+<p><strong>Note</strong>: You can find this <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/basic-for-improved.html">example code on GitHub</a> too (also <a href="http://mdn.github.io/learning-area/javascript/building-blocks/loops/basic-for-improved.html">see it running live</a>).</p>
+</div>
+
+<div class="warning">
+<p><strong>Important</strong>: With for — as with all loops — you must make sure that the initializer is iterated so that it eventually reaches the exit condition. If not, the loop will go on forever, and either the browser will force it to stop, or it will crash. This is called an <strong>infinite loop</strong>.</p>
+</div>
+
+<h2 id="中斷退出循環">中斷退出循環</h2>
+
+<p>如果要在所有迭代完成之前退出循環,可以使用break語句。 在查看switch語句時,我們已經在上一篇文章中遇到了這一問題—當在switch語句中遇到與輸入表達式匹配的case時,break語句立即退出switch語句並移至其後的代碼上。</p>
+
+<p>循環也是如此,-break語句將立即退出循環,並使瀏覽器繼續執行緊隨其後的任何代碼。</p>
+
+<p>假設我們要搜索一系列聯繫人和電話號碼,然後僅返回我們要查找的號碼? 首先,提供一些簡單的HTML-文本 {{htmlelement(“ input”)}} 允許我們輸入要搜索的名稱,{{htmlelement(“ button”)}} 元素以提交搜索,以及 {{htmlelement (“ p”)}} 元素以在以下位置顯示結果:</p>
+
+<pre class="brush: html notranslate">&lt;label for="search"&gt;Search by contact name: &lt;/label&gt;
+&lt;input id="search" type="text"&gt;
+&lt;button&gt;Search&lt;/button&gt;
+
+&lt;p&gt;&lt;/p&gt;</pre>
+
+<p>Now on to the JavaScript:</p>
+
+<pre class="brush: js notranslate">var contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 'Dianne:9384975'];
+var para = document.querySelector('p');
+var input = document.querySelector('input');
+var btn = document.querySelector('button');
+
+btn.addEventListener('click', function() {
+ var searchName = input.value;
+ input.value = '';
+ input.focus();
+ for (var i = 0; i &lt; contacts.length; i++) {
+ var splitContact = contacts[i].split(':');
+ if (splitContact[0] === searchName) {
+ para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.';
+ break;
+ } else {
+ para.textContent = 'Contact not found.';
+ }
+ }
+});</pre>
+
+<div class="hidden">
+<h6 id="Hidden_code_3">Hidden code 3</h6>
+
+<pre class="brush: html notranslate">&lt;!DOCTYPE html&gt;
+&lt;html&gt;
+ &lt;head&gt;
+ &lt;meta charset="utf-8"&gt;
+ &lt;title&gt;Simple contact search example&lt;/title&gt;
+ &lt;style&gt;
+
+ &lt;/style&gt;
+ &lt;/head&gt;
+ &lt;body&gt;
+
+ &lt;label for="search"&gt;Search by contact name: &lt;/label&gt;
+ &lt;input id="search" type="text"&gt;
+ &lt;button&gt;Search&lt;/button&gt;
+
+ &lt;p&gt;&lt;/p&gt;
+
+
+ &lt;script&gt;
+ var contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 'Dianne:9384975'];
+ var para = document.querySelector('p');
+ var input = document.querySelector('input');
+ var btn = document.querySelector('button');
+
+ btn.addEventListener('click', function() {
+ var searchName = input.value;
+ input.value = '';
+ input.focus();
+ for (var i = 0; i &lt; contacts.length; i++) {
+ var splitContact = contacts[i].split(':');
+ if (splitContact[0] === searchName) {
+ para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.';
+ break;
+ } else if (i === contacts.length-1)
+  para.textContent = 'Contact not found.';
+  }
+ });
+ &lt;/script&gt;
+
+ &lt;/body&gt;
+&lt;/html&gt;</pre>
+</div>
+
+<p>{{ EmbedLiveSample('Hidden_code_3', '100%', 100, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<ol>
+ <li>首先,我們有一些變量定義-我們有一個聯繫信息陣列,每個項目都是一個字符串,其中包含用冒號分隔的姓名和電話號碼。</li>
+ <li>接下來,我們將事件監聽器附加到按鈕(btn),以便在按下按鈕時,將運行一些代碼來執行搜索並返回結果。</li>
+ <li>我們將輸入到文本輸入中的值存儲在一個名為searchName的變量中,然後清空文本輸入並再次對其進行聚焦,以準備進行下一次搜索。</li>
+ <li>現在到有趣的部分,for循環:
+ <ol>
+ <li>我們從0開始啟動計數器,運行循環直到計數器不再小於contact.length,然後在每次循環之後將i遞增1。</li>
+ <li>在循環內部,我們首先將當前觸點(contacts [i])分割為冒號字符,並將得到的兩個值存儲在名為 splitContact 的數組中。</li>
+ <li>然後,我們使用條件語句來測試splitContact [0](聯繫人的姓名)是否等於輸入的searchName。 如果是這樣,我們在段落中輸入一個字符串以報告聯繫人的電話號碼,然後使用break結束循環。</li>
+ </ol>
+ </li>
+ <li>
+ <p>在(contacts.length-1)迭代之後,如果聯繫人姓名與輸入的搜索不匹配,則將段落文本設置為“找不到聯繫人。”,然後循環繼續進行迭代。</p>
+ </li>
+</ol>
+
+<div class="note">
+<p>Note: You can view the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/contact-search.html">full source code on GitHub</a> too (also <a href="http://mdn.github.io/learning-area/javascript/building-blocks/loops/contact-search.html">see it running live</a>).</p>
+</div>
+
+<h2 id="Skipping_iterations_with_continue">Skipping iterations with continue</h2>
+
+<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Statements/continue">continue</a> statement works in a similar manner to <code>break</code>, but instead of breaking out of the loop entirely, it skips to the next iteration of the loop. Let's look at another example that takes a number as an input, and returns only the numbers that are squares of integers (whole numbers).</p>
+
+<p>The HTML is basically the same as the last example — a simple text input, and a paragraph for output. The JavaScript is mostly the same too, although the loop itself is a bit different:</p>
+
+<pre class="brush: js notranslate">var num = input.value;
+
+for (var i = 1; i &lt;= num; i++) {
+ var sqRoot = Math.sqrt(i);
+ if (Math.floor(sqRoot) !== sqRoot) {
+ continue;
+ }
+
+ para.textContent += i + ' ';
+}</pre>
+
+<p>Here's the output:</p>
+
+<div class="hidden">
+<h6 id="Hidden_code_4">Hidden code 4</h6>
+
+<pre class="brush: html notranslate">&lt;!DOCTYPE html&gt;
+&lt;html&gt;
+ &lt;head&gt;
+ &lt;meta charset="utf-8"&gt;
+ &lt;title&gt;Integer squares generator&lt;/title&gt;
+ &lt;style&gt;
+
+ &lt;/style&gt;
+ &lt;/head&gt;
+ &lt;body&gt;
+
+ &lt;label for="number"&gt;Enter number: &lt;/label&gt;
+ &lt;input id="number" type="text"&gt;
+ &lt;button&gt;Generate integer squares&lt;/button&gt;
+
+ &lt;p&gt;Output: &lt;/p&gt;
+
+
+ &lt;script&gt;
+ var para = document.querySelector('p');
+ var input = document.querySelector('input');
+ var btn = document.querySelector('button');
+
+ btn.addEventListener('click', function() {
+ para.textContent = 'Output: ';
+ var num = input.value;
+ input.value = '';
+ input.focus();
+ for (var i = 1; i &lt;= num; i++) {
+ var sqRoot = Math.sqrt(i);
+ if (Math.floor(sqRoot) !== sqRoot) {
+ continue;
+ }
+
+ para.textContent += i + ' ';
+ }
+ });
+ &lt;/script&gt;
+
+ &lt;/body&gt;
+&lt;/html&gt;</pre>
+</div>
+
+<p>{{ EmbedLiveSample('Hidden_code_4', '100%', 100, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<ol>
+ <li>In this case, the input should be a number (<code>num</code>). The <code>for</code> loop is given a counter starting at 1 (as we are not interested in 0 in this case), an exit condition that says the loop will stop when the counter becomes bigger than the input <code>num</code>, and an iterator that adds 1 to the counter each time.</li>
+ <li>Inside the loop, we find the square root of each number using <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt">Math.sqrt(i)</a>, then check whether the square root is an integer by testing whether it is the same as itself when it has been rounded down to the nearest integer (this is what <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor">Math.floor()</a> does to the number it is passed).</li>
+ <li>If the square root and the rounded down square root do not equal one another (<code>!==</code>), it means that the square root is not an integer, so we are not interested in it. In such a case, we use the <code>continue</code> statement to skip on to the next loop iteration without recording the number anywhere.</li>
+ <li>If the square root IS an integer, we skip past the if block entirely so the <code>continue</code> statement is not executed; instead, we concatenate the current <code>i</code> value plus a space on to the end of the paragraph content.</li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: You can view the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/integer-squares.html">full source code on GitHub</a> too (also <a href="http://mdn.github.io/learning-area/javascript/building-blocks/loops/integer-squares.html">see it running live</a>).</p>
+</div>
+
+<h2 id="while_and_do_..._while">while and do ... while</h2>
+
+<p><code>for</code> is not the only type of loop available in JavaScript. There are actually many others and, while you don't need to understand all of these now, it is worth having a look at the structure of a couple of others so that you can recognize the same features at work in a slightly different way.</p>
+
+<p>First, let's have a look at the <a href="/en-US/docs/Web/JavaScript/Reference/Statements/while">while</a> loop. This loop's syntax looks like so:</p>
+
+<pre class="notranslate">initializer
+while (exit-condition) {
+ // code to run
+
+ final-expression
+}</pre>
+
+<p>This works in a very similar way to the for loop, except that the initializer variable is set before the loop, and the final-expression is included inside the loop after the code to run — rather than these two items being included inside the parentheses. The exit-condition is included inside the parentheses, which are preceded by the <code>while</code> keyword rather than <code>for</code>.</p>
+
+<p>The same three items are still present, and they are still defined in the same order as they are in the for loop — this makes sense, as you still have to have an initializer defined before you can check whether it has reached the exit-condition; the final-condition is then run after the code inside the loop has run (an iteration has been completed), which will only happen if the exit-condition has still not been reached.</p>
+
+<p>Let's have a look again at our cats list example, but rewritten to use a while loop:</p>
+
+<pre class="brush: js notranslate">var i = 0;
+
+while (i &lt; cats.length) {
+ if (i === cats.length - 1) {
+ info += 'and ' + cats[i] + '.';
+ } else {
+ info += cats[i] + ', ';
+ }
+
+ i++;
+}</pre>
+
+<div class="note">
+<p><strong>Note</strong>: This still works just the same as expected — have a look at it <a href="http://mdn.github.io/learning-area/javascript/building-blocks/loops/while.html">running live on GitHub</a> (also view the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/while.html">full source code</a>).</p>
+</div>
+
+<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Statements/do...while">do...while</a> loop is very similar, but provides a variation on the while structure:</p>
+
+<pre class="notranslate">initializer
+do {
+ // code to run
+
+ final-expression
+} while (exit-condition)</pre>
+
+<p>In this case, the initializer again comes first, before the loop starts. The <code>do</code> keyword directly precedes the curly braces containing the code to run and the final-expression.</p>
+
+<p>The differentiator here is that the exit-condition comes after everything else, wrapped in parentheses and preceded by a <code>while</code> keyword. In a <code>do...while</code> loop, the code inside the curly braces is always run once before the check is made to see if it should be executed again (in while and for, the check comes first, so the code might never be executed).</p>
+
+<p>Let's rewrite our cat listing example again to use a <code>do...while</code> loop:</p>
+
+<pre class="brush: js notranslate">var i = 0;
+
+do {
+ if (i === cats.length - 1) {
+ info += 'and ' + cats[i] + '.';
+ } else {
+ info += cats[i] + ', ';
+ }
+
+ i++;
+} while (i &lt; cats.length);</pre>
+
+<div class="note">
+<p><strong>Note</strong>: Again, this works just the same as expected — have a look at it <a href="http://mdn.github.io/learning-area/javascript/building-blocks/loops/do-while.html">running live on GitHub</a> (also view the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/do-while.html">full source code</a>).</p>
+</div>
+
+<div class="warning">
+<p><strong>Important</strong>: With while and do...while — as with all loops — you must make sure that the initializer is iterated so that it eventually reaches the exit condition. If not, the loop will go on forever, and either the browser will force it to stop, or it will crash. This is called an <strong>infinite loop</strong>.</p>
+</div>
+
+<h2 id="Active_learning_Launch_countdown!">Active learning: Launch countdown!</h2>
+
+<p>In this exercise, we want you to print out a simple launch countdown to the output box, from 10 down to Blast off. Specifically, we want you to:</p>
+
+<ul>
+ <li>Loop from 10 down to 0. We've provided you with an initializer — <code>var i = 10;</code>.</li>
+ <li>For each iteration, create a new paragraph and append it to the output <code>&lt;div&gt;</code>, which we've selected using <code>var output = document.querySelector('.output');</code>. In comments, we've provided you with three code lines that need to be used somewhere inside the loop:
+ <ul>
+ <li><code>var para = document.createElement('p');</code> — creates a new paragraph.</li>
+ <li><code>output.appendChild(para);</code> — appends the paragraph to the output <code>&lt;div&gt;</code>.</li>
+ <li><code>para.textContent =</code> — makes the text inside the paragraph equal to whatever you put on the right hand side, after the equals sign.</li>
+ </ul>
+ </li>
+ <li>Different iteration numbers require different text to be put in the paragraph for that iteration (you'll need a conditional statement and multiple <code>para.textContent =</code> lines):
+ <ul>
+ <li>If the number is 10, print "Countdown 10" to the paragraph.</li>
+ <li>If the number is 0, print "Blast off!" to the paragraph.</li>
+ <li>For any other number, print just the number to the paragraph.</li>
+ </ul>
+ </li>
+ <li>Remember to include an iterator! However, in this example we are counting down after each iteration, not up, so you <strong>don't</strong> want <code>i++</code> — how do you iterate downwards?</li>
+</ul>
+
+<p>If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.</p>
+
+<div class="hidden">
+<h6 id="Active_learning">Active learning</h6>
+
+<pre class="brush: html notranslate">&lt;h2&gt;Live output&lt;/h2&gt;
+&lt;div class="output" style="height: 410px;overflow: auto;"&gt;
+
+&lt;/div&gt;
+
+&lt;h2&gt;Editable code&lt;/h2&gt;
+&lt;p class="a11y-label"&gt;Press Esc to move focus away from the code area (Tab inserts a tab character).&lt;/p&gt;
+&lt;textarea id="code" class="playable-code" style="height: 300px;width: 95%"&gt;
+var output = document.querySelector('.output');
+output.innerHTML = '';
+
+// var i = 10;
+
+// var para = document.createElement('p');
+// para.textContent = ;
+// output.appendChild(para);
+&lt;/textarea&gt;
+
+&lt;div class="playable-buttons"&gt;
+ &lt;input id="reset" type="button" value="Reset"&gt;
+ &lt;input id="solution" type="button" value="Show solution"&gt;
+&lt;/div&gt;
+</pre>
+
+<p class="brush: js"></p>
+
+<p class="brush: js"></p>
+
+<p class="brush: js"></p>
+
+<pre class="brush: css notranslate">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>
+
+<p class="brush: js"></p>
+
+<p class="brush: js"></p>
+
+<p class="brush: js"></p>
+
+<p class="brush: js"></p>
+
+<pre class="brush: js notranslate">var textarea = document.getElementById('code');
+var reset = document.getElementById('reset');
+var solution = document.getElementById('solution');
+var code = textarea.value;
+var 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();
+});
+
+var jsSolution = 'var output = document.querySelector(\'.output\');\noutput.innerHTML = \'\';\n\nvar i = 10;\n\nwhile(i &gt;= 0) {\n var para = document.createElement(\'p\');\n if(i === 10) {\n para.textContent = \'Countdown \' + i;\n } else if(i === 0) {\n para.textContent = \'Blast off!\';\n } else {\n para.textContent = i;\n }\n\n output.appendChild(para);\n\n i--;\n}';
+var 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) {
+ var scrollPos = textarea.scrollTop;
+ var caretPos = textarea.selectionStart;
+
+ var front = (textarea.value).substring(0, caretPos);
+ var 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>
+
+<p class="brush: js"></p>
+</div>
+
+<p>{{ EmbedLiveSample('Active_learning', '100%', 880, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<h2 id="Active_learning_Filling_in_a_guest_list">Active learning: Filling in a guest list</h2>
+
+<p>In this exercise, we want you to take a list of names stored in an array, and put them into a guest list. But it's not quite that easy — we don't want to let Phil and Lola in because they are greedy and rude, and always eat all the food! We have two lists, one for guests to admit, and one for guests to refuse.</p>
+
+<p>Specifically, we want you to:</p>
+
+<ul>
+ <li>Write a loop that will iterate from 0 to the length of the <code>people</code> array. You'll need to start with an initializer of  <code>var i = 0;</code>, but what exit condition do you need?</li>
+ <li>During each loop iteration, check if the current array item is equal to "Phil" or "Lola" using a conditional statement:
+ <ul>
+ <li>If it is, concatenate the array item to the end of the <code>refused</code> paragraph's <code>textContent</code>, followed by a comma and a space.</li>
+ <li>If it isn't, concatenate the array item to the end of the <code>admitted</code> paragraph's <code>textContent</code>, followed by a comma and a space.</li>
+ </ul>
+ </li>
+</ul>
+
+<p>We've already provided you with:</p>
+
+<ul>
+ <li><code>var i = 0;</code> — Your initializer.</li>
+ <li><code>refused.textContent +=</code> — the beginnings of a line that will concatenate something on to the end of <code>refused.textContent</code>.</li>
+ <li><code>admitted.textContent +=</code> — the beginnings of a line that will concatenate something on to the end of <code>admitted.textContent</code>.</li>
+</ul>
+
+<p>Extra bonus question — after completing the above tasks successfully, you will be left with two lists of names, separated by commas, but they will be untidy — there will be a comma at the end of each one. Can you work out how to write lines that slice the last comma off in each case, and add a full stop to the end? Have a look at the <a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a> article for help.</p>
+
+<p>If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.</p>
+
+<div class="hidden">
+<h6 id="Active_learning_2">Active learning 2</h6>
+
+<pre class="brush: html notranslate">&lt;h2&gt;Live output&lt;/h2&gt;
+&lt;div class="output" style="height: 100px;overflow: auto;"&gt;
+ &lt;p class="admitted"&gt;Admit: &lt;/p&gt;
+  &lt;p class="refused"&gt;Refuse: &lt;/p&gt;
+&lt;/div&gt;
+
+&lt;h2&gt;Editable code&lt;/h2&gt;
+&lt;p class="a11y-label"&gt;Press Esc to move focus away from the code area (Tab inserts a tab character).&lt;/p&gt;
+&lt;textarea id="code" class="playable-code" style="height: 400px;width: 95%"&gt;
+var people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce'];
+
+var admitted = document.querySelector('.admitted');
+var refused = document.querySelector('.refused');
+admitted.textContent = 'Admit: ';
+refused.textContent = 'Refuse: '
+
+// var i = 0;
+
+// refused.textContent += ;
+// admitted.textContent += ;
+
+&lt;/textarea&gt;
+
+&lt;div class="playable-buttons"&gt;
+ &lt;input id="reset" type="button" value="Reset"&gt;
+ &lt;input id="solution" type="button" value="Show solution"&gt;
+&lt;/div&gt;
+</pre>
+
+<pre class="brush: css notranslate">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 notranslate">var textarea = document.getElementById('code');
+var reset = document.getElementById('reset');
+var solution = document.getElementById('solution');
+var code = textarea.value;
+var 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();
+});
+
+var jsSolution = 'var people = [\'Chris\', \'Anne\', \'Colin\', \'Terri\', \'Phil\', \'Lola\', \'Sam\', \'Kay\', \'Bruce\'];\n\nvar admitted = document.querySelector(\'.admitted\');\nvar refused = document.querySelector(\'.refused\');\n\nadmitted.textContent = \'Admit: \';\nrefused.textContent = \'Refuse: \'\nvar i = 0;\n\ndo {\n if(people[i] === \'Phil\' || people[i] === \'Lola\') {\n refused.textContent += people[i] + \', \';\n } else {\n admitted.textContent += people[i] + \', \';\n }\n i++;\n} while(i &lt; people.length);\n\nrefused.textContent = refused.textContent.slice(0,refused.textContent.length-2) + \'.\';\nadmitted.textContent = admitted.textContent.slice(0,admitted.textContent.length-2) + \'.\';';
+var 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) {
+ var scrollPos = textarea.scrollTop;
+ var caretPos = textarea.selectionStart;
+
+ var front = (textarea.value).substring(0, caretPos);
+ var 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('Active_learning_2', '100%', 680, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<h2 id="Which_loop_type_should_you_use">Which loop type should you use?</h2>
+
+<p>For basic uses, <code>for</code>, <code>while</code>, and <code>do...while</code> loops are largely interchangeable. They can all be used to solve the same problems, and which one you use will largely depend on your personal preference — which one you find easiest to remember or most intuitive. Let's have a look at them again.</p>
+
+<p>First <code>for</code>:</p>
+
+<pre class="notranslate">for (initializer; exit-condition; final-expression) {
+ // code to run
+}</pre>
+
+<p><code>while</code>:</p>
+
+<pre class="notranslate">initializer
+while (exit-condition) {
+ // code to run
+
+ final-expression
+}</pre>
+
+<p>and finally <code>do...while</code>:</p>
+
+<pre class="notranslate">initializer
+do {
+ // code to run
+
+ final-expression
+} while (exit-condition)</pre>
+
+<p>We would recommend <code>for</code>, at least to begin with, as it is probably the easiest for remembering everything — the initializer, exit-condition, and final-expression all have to go neatly into the parentheses, so it is easy to see where they are and check that you aren't missing them.</p>
+
+<div class="note">
+<p><strong>Note</strong>: There are other loop types/features too, which are useful in advanced/specialized situations and beyond the scope of this article. If you want to go further with your loop learning, read our advanced <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">Loops and iteration guide</a>.</p>
+</div>
+
+<h2 id="Conclusion">Conclusion</h2>
+
+<p>This article has revealed to you the basic concepts behind, and different options available when, looping code in JavaScript. You should now be clear on why loops are a good mechanism for dealing with repetitive code, and be raring to use them in your own examples!</p>
+
+<p>If there is anything you didn't understand, feel free to read through the article again, or <a href="/en-US/Learn#Contact_us">contact us</a> to ask for help.</p>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">Loops and iteration in detail</a></li>
+ <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for statement reference</a></li>
+ <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/while">while</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/do...while">do...while</a> references</li>
+ <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/break">break</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/continue">continue</a> references</li>
+ <li>
+ <p class="entry-title"><a href="https://www.impressivewebs.com/javascript-for-loop/">What’s the Best Way to Write a JavaScript For Loop?</a> — some advanced loop best practices</p>
+ </li>
+</ul>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/Building_blocks/conditionals","Learn/JavaScript/Building_blocks/Functions", "Learn/JavaScript/Building_blocks")}}</p>
+
+<h2 id="In_this_module">In this module</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals">Making decisions in your code — conditionals</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code">Looping code</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">Functions — reusable blocks of code</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Build_your_own_function">Build your own function</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Return_values">Function return values</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events">Introduction to events</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Image_gallery">Image gallery</a></li>
+</ul>
diff --git a/files/zh-tw/learn/javascript/building_blocks/return_values/index.html b/files/zh-tw/learn/javascript/building_blocks/return_values/index.html
new file mode 100644
index 0000000000..f77f37d46c
--- /dev/null
+++ b/files/zh-tw/learn/javascript/building_blocks/return_values/index.html
@@ -0,0 +1,172 @@
+---
+title: 函數回傳值
+slug: Learn/JavaScript/Building_blocks/Return_values
+translation_of: Learn/JavaScript/Building_blocks/Return_values
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Build_your_own_function","Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}</div>
+
+<p class="summary">我們將在本課程中討論最後一個基本概念,即關閉函數 - 回傳值。 有些函數在完成後沒有回傳重要值,但其他函數會,並且了解它們的值是什麼,如何在代碼中使用它們以及如何使自己的自定義函數返回有用值非常重要。 我們將在下面介紹所有這些內容。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">Prerequisites:</th>
+ <td>
+ <p>Basic computer literacy, a basic understanding of HTML and CSS, <a href="/en-US/docs/Learn/JavaScript/First_steps">JavaScript first steps</a>, <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">Functions — reusable blocks of code</a>.</p>
+ </td>
+ </tr>
+ <tr>
+ <th scope="row">Objective:</th>
+ <td>To understand function return values, and how to make use of them.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="What_are_return_values">What are return values?</h2>
+
+<p><strong>Return values</strong> are just what they sound like — values returned by the function when it completes. You've already met return values a number of times, although you may not have thought about them explicitly. Let's return to some familiar code:</p>
+
+<pre class="brush: js">var myText = 'I am a string';
+var newString = myText.replace('string', 'sausage');
+console.log(newString);
+// the replace() string function takes a string,
+// replaces one substring with another, and returns
+// a new string with the replacement made</pre>
+
+<p>We saw exactly this block of code in our first function article. We are invoking the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace">replace()</a> function on the <code>myText</code> string, and passing it two parameters — the substring to find, and the substring to replace it with. When this function completes (finishes running), it returns a value, which is a new string with the replacement made. In the code above, we are saving this return value as the value of the <code>newString</code> variable.</p>
+
+<p>If you look at the replace function MDN reference page, you'll see a section called <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Return_value">Return value</a>. It is very useful to know and understand what values are returned by functions, so we try to include this information wherever possible.</p>
+
+<p>Some functions don't return a return value as such (in our reference pages, the return value is listed as <code>void</code> or <code>undefined</code> in such cases). For example, in the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/functions/function-stage-4.html#L50">displayMessage() function</a> we built in the previous article, no specific value is returned as a result of the function being invoked. It just makes a box appear somewhere on the screen — that's it!</p>
+
+<p>Generally, a return value is used where the function is an intermediate step in a calculation of some kind. You want to get to a final result, which involves some values. Those values need to be calculated by a function, which then returns the results so they can be used in the next stage of the calculation.</p>
+
+<h3 id="Using_return_values_in_your_own_functions">Using return values in your own functions</h3>
+
+<p>To return a value from a custom function, you need to use ... wait for it ... the <a href="/en-US/docs/Web/JavaScript/Reference/Statements/return">return</a> keyword. We saw this in action recently in our <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/loops/random-canvas-circles.html">random-canvas-circles.html</a> example. Our <code>draw()</code> function draws 100 random circles somewhere on an HTML {{htmlelement("canvas")}}:</p>
+
+<pre class="brush: js">function draw() {
+ ctx.clearRect(0,0,WIDTH,HEIGHT);
+ for (var i = 0; i &lt; 100; i++) {
+ ctx.beginPath();
+ ctx.fillStyle = 'rgba(255,0,0,0.5)';
+ ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+ ctx.fill();
+ }
+}</pre>
+
+<p>Inside each loop iteration, three calls are made to the <code>random()</code> function, to generate a random value for the current circle's x coordinate, y coordinate, and radius, respectively. The <code>random()</code> function takes one parameter — a whole number — and it returns a whole random number between 0 and that number. It looks like this:</p>
+
+<pre class="brush: js">function randomNumber(number) {
+ return Math.floor(Math.random()*number);
+}</pre>
+
+<p>This could be written as follows:</p>
+
+<pre class="brush: js">function randomNumber(number) {
+ var result = Math.floor(Math.random()*number);
+ return result;
+}</pre>
+
+<p>But the first version is quicker to write, and more compact.</p>
+
+<p>We are returning the result of the calculation <code>Math.floor(Math.random()*number)</code> each time the function is called. This return value appears at the point the function was called, and the code continues. So for example, if we ran the following line:</p>
+
+<pre class="brush: js">ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);</pre>
+
+<p>and the three <code>random()</code> calls returned the values 500, 200, and 35, respectively, the line would actually be run as if it were this:</p>
+
+<pre class="brush: js">ctx.arc(500, 200, 35, 0, 2 * Math.PI);</pre>
+
+<p>The function calls on the line are run first and their return values substituted for the function calls, before the line itself is then executed.</p>
+
+<h2 id="Active_learning_our_own_return_value_function">Active learning: our own return value function</h2>
+
+<p>Let's have a go at writing our own functions featuring return values.</p>
+
+<ol>
+ <li>First of all, make a local copy of the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/functions/function-library.html">function-library.html</a> file from GitHub. This is a simple HTML page containing a text {{htmlelement("input")}} field and a paragraph. There's also a {{htmlelement("script")}} element in which we have stored a reference to both HTML elements in two variables. This little page will allow you to enter a number into the text box, and display different numbers related to it in the paragraph below.</li>
+ <li>Let's add some useful functions to this <code>&lt;script&gt;</code> element. Below the existing two lines of JavaScript, add the following function definitions:
+ <pre class="brush: js">function squared(num) {
+ return num * num;
+}
+
+function cubed(num) {
+ return num * num * num;
+}
+
+function factorial(num) {
+ var x = num;
+ while (x &gt; 1) {
+ num *= x-1;
+ x--;
+ }
+ return num;
+}</pre>
+ The <code>squared()</code> and <code>cubed()</code> functions are fairly obvious — they return the square or cube of the number given as a parameter. The <code>factorial()</code> function returns the <a href="https://en.wikipedia.org/wiki/Factorial">factorial</a> of the given number.</li>
+ <li>Next, we're going to include a way to print out information about the number entered into the text input. Enter the following event handler below the existing functions:
+ <pre class="brush: js">input.onchange = function() {
+ var num = input.value;
+ if (isNaN(num)) {
+ para.textContent = 'You need to enter a number!';
+ } else {
+ para.textContent = num + ' squared is ' + squared(num) + '. ' +
+ num + ' cubed is ' + cubed(num) + '. ' +
+ num + ' factorial is ' + factorial(num) + '.';
+ }
+}</pre>
+
+ <p>Here we are creating an <code>onchange</code> event handler that runs whenever the change event fires on the text input — that is, when a new value is entered into the text input, and submitted (enter a value then press tab for example). When this anonymous function runs, the existing value entered into the input is stored in the <code>num</code> variable.</p>
+
+ <p>Next, we do a conditional test — if the entered value is not a number, we print an error message into the paragraph. The test looks at whether the expression <code>isNaN(num)</code> returns true. We use the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN">isNaN()</a> function to test whether the num value is not a number — if so, it returns <code>true</code>, and if not, <code>false</code>.</p>
+
+ <p>If the test returns <code>false</code>, the <code>num</code> value is a number, so we print out a sentence inside the paragraph element stating what the square, cube, and factorial of the number are. The sentence calls the <code>squared()</code>, <code>cubed()</code>, and <code>factorial()</code> functions to get the required values.</p>
+ </li>
+ <li>Save your code, load it in a browser, and try it out.</li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: If you have trouble getting the example to work, feel free to check your code against the <a href="https://github.com/mdn/learning-area/blob/master/javascript/building-blocks/functions/function-library-finished.html">finished version on GitHub</a> (<a href="http://mdn.github.io/learning-area/javascript/building-blocks/functions/function-library-finished.html">see it running live</a> also), or ask us for help.</p>
+</div>
+
+<p>At this point, we'd like you to have a go at writing out a couple of functions of your own and adding them to the library. How about the square or cube root of the number, or the circumference of a circle with a radius of length <code>num</code>?</p>
+
+<p>This exercise has brought up a couple of important points besides being a study on how to use the <code>return</code> statement. In addition, we have:</p>
+
+<ul>
+ <li>Looked at another example of writing error handling into our functions. It is generally a good idea to check that any necessary parameters have been provided, and in the right datatype, and if they are optional, that some kind of default value is provided to allow for that. This way, your program will be less likely to throw errors.</li>
+ <li>Thought about the idea of creating a function library. As you go further into your programming career, you'll start to do the same kinds of things over and over again. It is a good idea to start keeping your own library of utility functions that you use very often — you can then copy them over to your new code, or even just apply it to any HTML pages where you need it.</li>
+</ul>
+
+<h2 id="Conclusion">Conclusion</h2>
+
+<p>So there we have it — functions are fun, very useful and, although there's a lot to talk about in regards to their syntax and functionality, fairly understandable given the right articles to study.</p>
+
+<p>If there is anything you didn't understand, feel free to read through the article again, or <a href="/en-US/Learn#Contact_us">contact us</a> to ask for help.</p>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions">Functions in-depth</a> — a detailed guide covering more advanced functions-related information.</li>
+ <li><a href="https://www.impressivewebs.com/callback-functions-javascript/">Callback functions in JavaScript</a> — a common JavaScript pattern is to pass a function into another function as an argument, which is then called inside the first function. This is a little beyond the scope of this course, but worth studying before too long.</li>
+</ul>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Build_your_own_function","Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}</p>
+
+<p> </p>
+
+<h2 id="In_this_module">In this module</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals">Making decisions in your code — conditionals</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code">Looping code</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">Functions — reusable blocks of code</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Build_your_own_function">Build your own function</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Return_values">Function return values</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events">Introduction to events</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Image_gallery">Image gallery</a></li>
+</ul>
+
+<p> </p>
diff --git a/files/zh-tw/learn/javascript/client-side_web_apis/index.html b/files/zh-tw/learn/javascript/client-side_web_apis/index.html
new file mode 100644
index 0000000000..c678aae7ae
--- /dev/null
+++ b/files/zh-tw/learn/javascript/client-side_web_apis/index.html
@@ -0,0 +1,39 @@
+---
+title: 客戶端 web APIs
+slug: Learn/JavaScript/Client-side_web_APIs
+translation_of: Learn/JavaScript/Client-side_web_APIs
+---
+<div>{{LearnSidebar}}</div>
+
+<p class="summary">在為網站或應用程序編寫客戶端JavaScript時,您將很快遇到應用程式介面(API)。 API是應用程式介面,用於操作運行站點的瀏覽器和操作系統的不同方面,或操縱來自其他網站或服務的資料。 在本單元中,我們將探討API是什麼,以及如何使用您在開發工作中經常遇到的一些最常見的API。</p>
+
+<h2 id="必備知識">必備知識</h2>
+
+<p>To get the most out of this module, you should have worked your way through the previous JavaScript modules in the series (<a href="/en-US/docs/Learn/JavaScript/First_steps">First steps</a>, <a href="/en-US/docs/Learn/JavaScript/Building_blocks">Building blocks</a>, and <a href="/en-US/docs/Learn/JavaScript/Objects">JavaScript objects</a>). Those modules typically involve simple API usage, as it is often difficult to write client-side JavaScript examples without them. For this tutorial, we will assume that you are knowledgable about the core JavaScript language, and we will explore common Web APIs in a bit more detail.</p>
+
+
+
+<p>了解 <a href="/en-US/docs/Learn/HTML">HTML</a> 和 <a href="/en-US/docs/Learn/CSS">CSS</a> 的基礎知識也會有所幫助。</p>
+
+<div class="note">
+<p><strong>Note</strong>: 假如你正在使用 電腦/平板/其他裝置,你不需要建立自己的檔案,你可以嘗試線上程式撰寫系統來撰寫範例程式,像是<a href="http://jsbin.com/">JSBin</a> or <a href="https://thimble.mozilla.org/">Thimble</a>.</p>
+</div>
+
+<h2 id="概觀">概觀</h2>
+
+<dl>
+ <dt><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction">Web API簡介</a></dt>
+ <dd>First up, we'll start by looking at APIs from a high level — what are they, how do they work, how do you use them in your code, and how are they structured? We'll also take a look at what the different main classes of APIs are, and what kind of uses they have.</dd>
+ <dt><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents">文檔操作</a></dt>
+ <dd>When writing web pages and apps, one of the most common things you'll want to do is manipulate web documents in some way. This is usually done by using the Document Object Model (DOM), a set of APIs for controlling HTML and styling information that makes heavy use of the {{domxref("Document")}} object. In this article, we'll look at how to use the DOM in detail, along with some other interesting APIs that can alter your environment in interesting ways.</dd>
+ <dt><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data">從服務器獲取數據</a></dt>
+ <dd>Another very common task in modern websites and applications is retrieving individual data items from the server to update sections of a webpage without having to load an entirely new page. This seemingly small detail has had a huge impact on the performance and behavior of sites.  In this article, we'll explain the concept, and look at technologies that make it possible, such as {{domxref("XMLHttpRequest")}} and the <a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a>.</dd>
+ <dt><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Third_party_APIs">第三方API</a></dt>
+ <dd>The APIs we've covered so far are built into the browser, but not all APIs are. Many large websites and services such as Google Maps, Twitter, Facebook, PayPal, etc. provide APIs allowing developers to make use of their data (e.g. displaying your twitter stream on your blog) or services (e.g. displaying custom Google Maps on your site, or using Facebook login to log in your users). This article looks at the difference between browser APIs and 3rd party APIs and shows some typical uses of the latter.</dd>
+ <dt><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Drawing_graphics">繪製圖形</a></dt>
+ <dd>The browser contains some very powerful graphics programming tools, from the Scalable Vector Graphics (<a href="/en-US/docs/Web/SVG">SVG</a>) language, to APIs for drawing on HTML {{htmlelement("canvas")}} elements, (see <a href="/en-US/docs/Web/API/Canvas_API">The Canvas API</a> and <a href="/en-US/docs/Web/API/WebGL_API">WebGL</a>). This article provides an introduction to the Canvas API, and further resources to allow you to learn more.</dd>
+ <dt><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Video_and_audio_APIs">視頻和音頻API</a></dt>
+ <dd>HTML5 comes with elements for embedding rich media in documents — {{htmlelement("video")}} and {{htmlelement("audio")}} — which in turn come with their own APIs for controlling playback, seeking, etc. This article shows you how to do common tasks such as creating custom playback controls.</dd>
+ <dt><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage">客戶端存儲</a></dt>
+ <dd>Modern web browsers feature a number of different technologies that allow you to store data related to web sites and retrieve it when necessary allowing you to persist data long term, save sites offline, and more. This article explains the very basics of how these work.</dd>
+</dl>
diff --git a/files/zh-tw/learn/javascript/client-side_web_apis/manipulating_documents/index.html b/files/zh-tw/learn/javascript/client-side_web_apis/manipulating_documents/index.html
new file mode 100644
index 0000000000..5b04033cb1
--- /dev/null
+++ b/files/zh-tw/learn/javascript/client-side_web_apis/manipulating_documents/index.html
@@ -0,0 +1,314 @@
+---
+title: 文檔操作(文件操作)
+slug: Learn/JavaScript/Client-side_web_APIs/Manipulating_documents
+translation_of: Learn/JavaScript/Client-side_web_APIs/Manipulating_documents
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/Client-side_web_APIs/Introduction", "Learn/JavaScript/Client-side_web_APIs/Fetching_data", "Learn/JavaScript/Client-side_web_APIs")}}</div>
+
+<p class="summary">當你在撰寫網頁(web pages)或網路應用程式(web apps),其中一個最常見的事,你會希望能夠操作(網頁)文件結構。最常看見的方式是基於<a href="/zh-TW/docs/Web/API/Document_Object_Model"><strong>文件物件模型</strong> ( Document Object Model, DOM )</a> 概念上,透過使用 API (<a href="/zh-TW/docs/Web/API/">Web APIs</a>) 來控制 HTML 及 樣式;而這種方式也被大量使用在操作 <code><a href="/zh-TW/docs/Web/API/Document">Document</a></code> 物件上。接下來的文章中,我們將會詳細的介紹如何操作 DOM,藉著使用有趣的 API 能帶來些新奇的體驗。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">你事先需要了解:</th>
+ <td>基礎電腦知識, 了解基礎 HTML、CSS、JavaScript 概念 — 包含 JavaScript 物件概念.</td>
+ </tr>
+ <tr>
+ <th scope="row">你將學會:</th>
+ <td>更加熟悉 DOM 核心 API, 和常用來操作 DOM 的 API</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="The_important_parts_of_a_web_browser">The important parts of a web browser</h2>
+
+<p>Web browsers are very complicated pieces of software with a lot of moving parts, many of which can't be controlled or manipulated by a web developer using JavaScript. You might think that such limitations are a bad thing, but browsers are locked down for good reasons, mostly centering around security. Imagine if a web site could get access to your stored passwords or other sensitive information, and log into websites as if it were you?</p>
+
+<p>Despite the limitations, Web APIs still give us access to a lot of functionality that enable us to do a great many things with web pages. There are a few really obvious bits you'll reference regularly in your code — consider the following diagram, which represents the main parts of a browser directly involved in viewing web pages:</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/14557/document-window-navigator.png" style="display: block; margin: 0 auto;"></p>
+
+<ul>
+ <li>The window is the browser tab that a web page is loaded into; this is represented in JavaScript by the {{domxref("Window")}} object. Using methods available on this object you can do things like return the window's size (see {{domxref("Window.innerWidth")}} and {{domxref("Window.innerHeight")}}), manipulate the document loaded into that window, store data specific to that document on the client-side (for example using a local database or other storage mechanism), attach an <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#A_series_of_fortunate_events">event handler</a> to the current window, and more.</li>
+ <li>The navigator represents the state and identity of the browser (i.e. the user-agent) as it exists on the web. In JavaScript, this is represented by the {{domxref("Navigator")}} object. You can use this object to retrieve things like the user's preferred language, a media stream from the user's webcam, etc.</li>
+ <li>The document (represented by the DOM in browsers) is the actual page loaded into the window, and is represented in JavaScript by the {{domxref("Document")}} object. You can use this object to return and manipulate information on the HTML and CSS that comprises the document, for example get a reference to an element in the DOM, change its text content, apply new styles to it, create new elements and add them to the current element as children, or even delete it altogether.</li>
+</ul>
+
+<p>In this article we'll focus mostly on manipulating the document, but we'll show a few other useful bits besides.</p>
+
+<h2 id="The_document_object_model">The document object model</h2>
+
+<p>The document currently loaded in each one of your browser tabs is represented by a document object model. This is a "tree structure" representation created by the browser that enables the HTML structure to be easily accessed by programming languages — for example the browser itself uses it to apply styling and other information to the correct elements as it renders a page, and developers like you can manipulate the DOM with JavaScript after the page has been rendered.</p>
+
+<p>We have created a simple example page at <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/document-manipulation/dom-example.html">dom-example.html</a> (<a href="http://mdn.github.io/learning-area/javascript/apis/document-manipulation/dom-example.html">see it live also</a>). Try opening this up in your browser — it is a very simple page containing a {{htmlelement("section")}} element inside which you can find an image, and a paragraph with a link inside. The HTML source code looks like this:</p>
+
+<pre class="brush: html">&lt;!DOCTYPE html&gt;
+&lt;html&gt;
+ &lt;head&gt;
+ &lt;meta charset="utf-8"&gt;
+ &lt;title&gt;Simple DOM example&lt;/title&gt;
+ &lt;/head&gt;
+ &lt;body&gt;
+ &lt;section&gt;
+ &lt;img src="dinosaur.png" alt="A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth."&gt;
+ &lt;p&gt;Here we will add a link to the &lt;a href="https://www.mozilla.org/"&gt;Mozilla homepage&lt;/a&gt;&lt;/p&gt;
+ &lt;/section&gt;
+ &lt;/body&gt;
+&lt;/html&gt;</pre>
+
+<p>The DOM on the other hand looks like this:</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/14559/dom-screenshot.png" style="border-style: solid; border-width: 1px; display: block; margin: 0px auto;"></p>
+
+<div class="note">
+<p><strong>Note</strong>: This DOM tree diagram was created using Ian Hickson's <a href="https://software.hixie.ch/utilities/js/live-dom-viewer/">Live DOM viewer</a>.</p>
+</div>
+
+<p>You can see here that each element and bit of text in the document has its own entry in the tree — each one is called a <strong>node</strong>. You will also encounter various terms used to describe the type of node, and their position in the tree in relation to one another:</p>
+
+<ul>
+ <li><strong>Element node</strong>: An element, as it exists in the DOM.</li>
+ <li><strong>Root node</strong>: The top node in the tree, which in the case of HTML is always the <code>HTML</code> node (other markup vocabularies like SVG and custom XML will have different root elements).</li>
+ <li><strong>Child node</strong>: A node <em>directly</em> inside another node. For example, <code>IMG</code> is a child of <code>SECTION</code> in the above example.</li>
+ <li><strong>Descendant node</strong>: A node <em>anywhere</em> inside another node. For example, <code>IMG</code> is a child of <code>SECTION</code> in the above example, and it is also a descendant. <code>IMG</code> is not a child of <code>BODY</code>, as it is two levels below it in the tree, but it is a descendant of <code>BODY</code>.</li>
+ <li><strong>Parent node</strong>: A node which has another node inside it. For example, <code>BODY</code> is the parent node of <code>SECTION</code> in the above example.</li>
+ <li><strong>Sibling nodes</strong>: Nodes that sit on the same level in the DOM tree. For example, <code>IMG</code> and <code>P</code> are siblings in the above example.</li>
+ <li><strong>Text node</strong>: A node containing a text string.</li>
+</ul>
+
+<p>It is useful to familiarize yourself with this terminology before working with the DOM, as a number of the code terms you'll come across make use of them. You may have also come across them if you have studied CSS (e.g. descendant selector, child selector).</p>
+
+<h2 id="Active_learning_Basic_DOM_manipulation">Active learning: Basic DOM manipulation</h2>
+
+<p>To start learning about DOM manipulation, let's begin with a practical example.</p>
+
+<ol>
+ <li>Take a local copy of the <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/document-manipulation/dom-example.html">dom-example.html page</a> and the <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/document-manipulation/dinosaur.png">image</a> that goes along with it.</li>
+ <li>Add a <code>&lt;script&gt;&lt;/script&gt;</code> element just above the closing <code>&lt;/body&gt;</code> tag.</li>
+ <li>To manipulate an element inside the DOM, you first need to select it and store a reference to it inside a variable. Inside your script element, add the following line:
+ <pre class="brush: js">var link = document.querySelector('a');</pre>
+ </li>
+ <li>Now we have the element reference stored in a variable, we can start to manipulate it using properties and methods available to it (these are defined on interfaces like {{domxref("HTMLAnchorElement")}} in the case of {{htmlelement("a")}} element, its more general parent interface {{domxref("HTMLElement")}}, and {{domxref("Node")}} — which represents all nodes in a DOM). First of all, let's change the text inside the link by updating the value of the {{domxref("Node.textContent")}} property. Add the following line below the previous one:
+ <pre class="brush: js">link.textContent = 'Mozilla Developer Network';</pre>
+ </li>
+ <li>We should also change the URL the link is pointing to, so that it doesn't go to the wrong place when it is clicked on. Add the following line, again at the bottom:
+ <pre class="brush: js">link.href = 'https://developer.mozilla.org';</pre>
+ </li>
+</ol>
+
+<div>
+<p>Note that, as with many things in JavaScript, there are many ways to select an element and store a reference to it in a variable. {{domxref("Document.querySelector()")}} is the recommended modern approach, which is convenient because it allows you to select elements using CSS selectors. The above <code>querySelector()</code> call will match the first {{htmlelement("a")}} element that appears in the document. If you wanted to match and do things to multiple elements, you could use {{domxref("Document.querySelectorAll()")}}, which matches every element in the document that matches the selector, and stores references to them in an <a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">array</a>-like object called a NodeList.</p>
+
+<p>There are older methods available for grabbing element references, such as:</p>
+
+<ul>
+ <li>{{domxref("Document.getElementById()")}}, which selects an element with a given <code>id</code> attribute value, e.g. <code>&lt;p id="myId"&gt;My paragraph&lt;/p&gt;</code>. The ID is passed to the function as a parameter, i.e. <code>var elementRef = document.getElementById('myId')</code>.</li>
+ <li>{{domxref("Document.getElementsByTagName()")}}, which returns an array containing all the elements on the page of a given type, for example <code>&lt;p&gt;</code>s, <code>&lt;a&gt;</code>s, etc. The element type is passed to the function as a parameter, i.e. <code>var elementRefArray = document.getElementsByTagName('p')</code>.</li>
+</ul>
+
+<p>These two work in older browsers than the modern methods like <code>querySelector()</code>, but are not as convenient. Have a look and see what others you can find!</p>
+</div>
+
+<h3 id="Creating_and_placing_new_nodes">Creating and placing new nodes</h3>
+
+<p>The above has given you a little taste of what you can do, but let's go further and look at how we can create new elements.</p>
+
+<ol>
+ <li>Going back to the current example, let's start by grabbing a reference to the our {{htmlelement("section")}} element — add the following code at the bottom of your existing script (do the same with the other lines too):
+ <pre class="brush: js">var sect = document.querySelector('section');</pre>
+ </li>
+ <li>Now let's create a new paragraph using {{domxref("Document.createElement()")}} and give it some text content in the same way as before:
+ <pre class="brush: js">var para = document.createElement('p');
+para.textContent = 'We hope you enjoyed the ride.';</pre>
+ </li>
+ <li>You can now append the new paragraph at the end of the section using {{domxref("Node.appendChild()")}}:
+ <pre class="brush: js">sect.appendChild(para);</pre>
+ </li>
+ <li>Finally for this part, let's add a text node to the paragraph the link sits inside, to round off the sentence nicely. First we will create the text node using {{domxref("Document.createTextNode()")}}:
+ <pre class="brush: js">var text = document.createTextNode(' — the premier source for web development knowledge.');</pre>
+ </li>
+ <li>Now we'll grab a reference to the paragraph the link is inside, and append the text node to it:
+ <pre class="brush: js">var linkPara = document.querySelector('p');
+linkPara.appendChild(text);</pre>
+ </li>
+</ol>
+
+<p>That's most of what you need for adding nodes to the DOM — you'll make a lot of use of these methods when building dynamic interfaces (we'll look at some examples later).</p>
+
+<h3 id="Moving_and_removing_elements">Moving and removing elements</h3>
+
+<p>There may be times when you want to move nodes, or delete them from the DOM altogether. This is perfectly possible.</p>
+
+<p>If we wanted to move the paragraph with the link inside it to the bottom of the section, we could simply do this:</p>
+
+<pre class="brush: js">sect.appendChild(linkPara);</pre>
+
+<p>This moves the paragraph down to the bottom of the section. You might have thought it would make a second copy of it, but this is not the case — <code>linkPara</code> is a reference to the one and only copy of that paragraph. If you wanted to make a copy and add that as well, you'd need to use {{domxref("Node.cloneNode()")}} instead.</p>
+
+<p>Removing a node is pretty simple as well, at least when you have a reference to the node to be removed and its parent. In our current case, we just use {{domxref("Node.removeChild()")}}, like this:</p>
+
+<pre class="brush: js">sect.removeChild(linkPara);</pre>
+
+<p>It gets slightly more complex when you want to remove a node based only on a reference to itself, which is fairly common. There is no method to tell a node to remove itself, so you'd have to do the following.</p>
+
+<pre class="brush: js">linkPara.parentNode.removeChild(linkPara);</pre>
+
+<p>Have a go at adding the above lines to your code.</p>
+
+<h3 id="Manipulating_styles">Manipulating styles</h3>
+
+<p>It is possible to manipulate CSS styles via JavaScript in a variety of ways.</p>
+
+<p>To start with, you can get a list of all the stylesheets attached to a document using {{domxref("Document.stylesheets")}}, which returns an array of {{domxref("CSSStyleSheet")}} objects. You can then add/remove styles as wished. However, we're not going to expand on those features because they are a somewhat archaic and difficult way to manipulate style. There are much easier ways.</p>
+
+<p>The first way is to add inline styles directly onto elements you want to dynamically style. This is done with the {{domxref("HTMLElement.style")}} property, which contains inline styling information for each element in the document. You can set properties of this object to directly update element styles.</p>
+
+<ol>
+ <li>As an example, try adding these lines to our ongoing example:
+ <pre class="brush: js">para.style.color = 'white';
+para.style.backgroundColor = 'black';
+para.style.padding = '10px';
+para.style.width = '250px';
+para.style.textAlign = 'center';</pre>
+ </li>
+ <li>Reload the page and you'll see that the styles have been applied to the paragraph. If you look at that paragraph in your browser's <a href="/en-US/docs/Tools/Page_Inspector">Page Inspector/DOM inspector</a>, you'll see that these lines are indeed adding inline styles to the document:
+ <pre class="brush: html">&lt;p style="color: white; background-color: black; padding: 10px; width: 250px; text-align: center;"&gt;We hope you enjoyed the ride.&lt;/p&gt;</pre>
+ </li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: Notice how the JavaScript property versions of the CSS styles are written in lower camel case whereas the CSS versions are hyphenated (e.g. <code>backgroundColor</code> versus <code>background-color</code>). Make sure you don't get these mixed up, otherwise it won't work.</p>
+</div>
+
+<p>There is another common way to dynamically manipulate styles on your document, which we'll look at now.</p>
+
+<ol>
+ <li>Delete the previous five lines you added to the JavaScript.</li>
+ <li>Add the following inside your HTML {{htmlelement("head")}}:
+ <pre>&lt;style&gt;
+.highlight {
+ color: white;
+ background-color: black;
+ padding: 10px;
+ width: 250px;
+ text-align: center;
+}
+&lt;/style&gt;</pre>
+ </li>
+ <li>Now we'll turn to a very useful method for general HTML manipulation — {{domxref("Element.setAttribute()")}} — this takes two arguments, the attribute you want to set on the element, and the value you want to set it to. In this case we will set a class name of highlight on our paragraph:
+ <pre class="brush: js">para.setAttribute('class', 'highlight');</pre>
+ </li>
+ <li>Refresh your page, and you'll see no change — the CSS is still applied to the paragraph, but this time by giving it a class that is selected by our CSS rule, not as inline CSS styles.</li>
+</ol>
+
+<p>Which method you choose is up to you; both have their advantages and disadvantages. The first method takes less setup and is good for simple uses, whereas the second method is more purist (no mixing CSS and JavaScript, no inline styles, which are seen as a bad practice). As you start building larger and more involved apps, you will probably start using the second method more, but it is really up to you.</p>
+
+<p>At this point, we haven't really done anything useful! There is no point using JavaScript to create static content — you might as well just write it into your HTML and not use JavaScript. It is more complex than HTML, and creating your content with JavaScript also has other issues attached to it (such as not being readable by search engines).</p>
+
+<p>In the next couple of sections we will look at a couple of more practical uses of DOM APIs.</p>
+
+<div class="note">
+<p><strong>Note</strong>: You can find our <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/document-manipulation/dom-example-manipulated.html">finished version of the dom-example.html</a> demo on GitHub (<a href="http://mdn.github.io/learning-area/javascript/apis/document-manipulation/dom-example-manipulated.html">see it live also</a>).</p>
+</div>
+
+<h2 id="Active_learning_Getting_useful_information_from_the_Window_object">Active learning: Getting useful information from the Window object</h2>
+
+<p>So far we've only really looked at using {{domxref("Node")}} and {{domxref("Document")}} features to manipulate documents, but there is no reason why you can't get data from other sources and use it in your UI. Think back to our simple <a href="http://mdn.github.io/learning-area/javascript/apis/introduction/maps-example.html">maps-example.html</a> demo from the last article — there we retrieved some location data and used it to display a map of your area. You just have to make sure your data is in the right format; JavaScript makes it easier than many other languages, being weakly typed — for example numbers will convert to strings automatically when you want to print them to the screen.</p>
+
+<p>In this example we will solve a common problem — making sure your application is as big as the window it is viewed in, whatever size it is. This is often useful in situations like games, where you want to use as much of the screen area as possible to play the game in.</p>
+
+<p>To start with, make a local copy of our <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/document-manipulation/window-resize-example.html">window-resize-example.html</a> and <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/document-manipulation/bgtile.png">bgtile.png</a> demo files. Open it and have a look — you'll see that we've got a {{htmlelement("div")}} element covering a small part of the screen, which has got a background tile applied to it. We'll use that to represent our app UI area.</p>
+
+<ol>
+ <li>First of all, let's grab a reference to the div, and then grab the width and height of the viewport (the inner window, where your document is displayed) and store them in variables — these two values are handily contained in the {{domxref("Window.innerWidth")}} and {{domxref("Window.innerHeight")}} properties. Add the following lines inside the existing {{htmlelement("script")}} element:
+ <pre class="brush: js">var div = document.querySelector('div');
+var WIDTH = window.innerWidth;
+var HEIGHT = window.innerHeight;</pre>
+ </li>
+ <li>Next, we'll dynamically alter the width and height of the div to equal that of the viewport. Add the following two lines below your first ones:
+ <pre class="brush: js">div.style.width = WIDTH + 'px';
+div.style.height = HEIGHT + 'px';</pre>
+ </li>
+ <li>Save and try refreshing your browser — you should now see the div become as big as your viewport, whatever size of screen your are using. If you now try resizing your window to make it bigger, you'll see that the div stays the same size — we are only setting it once.</li>
+ <li>How about we use an event so that the div resizes as we resize the window? The {{domxref("Window")}} object has an event available on it called resize, which is fired every time the window is resized — let's access that via the {{domxref("Window.onresize")}} event handler and rerun our sizing code each time it changes. Add the following to the bottom of your code:
+ <pre class="brush: js">window.onresize = function() {
+ WIDTH = window.innerWidth;
+ HEIGHT = window.innerHeight;
+ div.style.width = WIDTH + 'px';
+ div.style.height = HEIGHT + 'px';
+}</pre>
+ </li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: If you get stuck, have a look at our <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/document-manipulation/window-resize-example-finished.html">finished window resize example</a> (<a href="http://mdn.github.io/learning-area/javascript/apis/document-manipulation/window-resize-example-finished.html">see it live also</a>).</p>
+</div>
+
+<h2 id="Active_learning_A_dynamic_shopping_list">Active learning: A dynamic shopping list</h2>
+
+<p>To round off the article, we'd like to set you a little challenge — we want to make a simple shopping list example that allows you to dynamically add items to the list using a form input and button. When you add an item to the input and press the button:</p>
+
+<ul>
+ <li>The item should appear in the list.</li>
+ <li>Each item should be given a button that can be pressed to delete that item off the list.</li>
+ <li>The input should be emptied and focused ready for you to enter another item.</li>
+</ul>
+
+<p>The finished demo will look something like this:</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/14563/shopping-list.png" style="border-style: solid; border-width: 1px; display: block; height: 225px; margin: 0px auto; width: 369px;"></p>
+
+<p>To complete the exercise, follow the steps below, and make sure that the list behaves as described above.</p>
+
+<ol>
+ <li>To start with, download a copy of our <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/document-manipulation/shopping-list.html">shopping-list.html</a> starting file and make a copy of it somewhere. You'll see that it has some minimal CSS, a list with a label, input, and button, and an empty list and {{htmlelement("script")}} element. You'll be making all your additions inside the script.</li>
+ <li>Create three variables that hold references to the list ({{htmlelement("ul")}}), {{htmlelement("input")}}, and {{htmlelement("button")}} elements.</li>
+ <li>Create a <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">function</a> that will run in response to the button being clicked.</li>
+ <li>Inside the function body, start off by storing the current <a href="/en-US/docs/Web/API/HTMLInputElement#Properties">value</a> of the input element in a variable.</li>
+ <li>Next, empty the input element by setting its value to an empty string — <code>''</code>.</li>
+ <li>Create three new elements — a list item ({{htmlelement('li')}}), {{htmlelement('span')}}, and {{htmlelement('button')}}, and store them in variables.</li>
+ <li>Append the span and the button as children of the list item.</li>
+ <li>Set the text content of the span to the input element value you saved earlier, and the text content of the button to 'Delete'.</li>
+ <li>Append the list item as a child of the list.</li>
+ <li>Attach an event handler to the delete button, so that when clicked it will delete the entire list item it is inside.</li>
+ <li>Finally, use the <code><a href="/en-US/docs/Web/API/HTMLElement/focus">focus()</a></code> method to focus the input element ready for entering the next shopping list item.</li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: If you get really stuck, have a look at our <a href="https://github.com/mdn/learning-area/blob/master/javascript/apis/document-manipulation/shopping-list-finished.html">finished shopping list</a> (<a href="http://mdn.github.io/learning-area/javascript/apis/document-manipulation/shopping-list-finished.html">see it running live also</a>.)</p>
+</div>
+
+<h2 id="Summary">Summary</h2>
+
+<p>We have reached the end of our study of document and DOM manipulation. At this point you should understand what the important parts of a web browser are with respect to controlling documents and other aspects of the user's web experience. Most importantly, you should understand what the Document Object Model is, and how to manipulate it to create useful functionality.</p>
+
+<h2 id="See_also">See also</h2>
+
+<p>There are lots more features you can use to manipulate your documents. Check out some of our references and see what you can discover:</p>
+
+<ul>
+ <li>{{domxref("Document")}}</li>
+ <li>{{domxref("Window")}}</li>
+ <li>{{domxref("Node")}}</li>
+ <li>{{domxref("HTMLElement")}}, {{domxref("HTMLInputElement")}}, {{domxref("HTMLImageElement")}}, etc.</li>
+</ul>
+
+<p>(See our <a href="https://developer.mozilla.org/en-US/docs/Web/API">Web API index</a> for the full list of Web APIs documented on MDN!)</p>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/Client-side_web_APIs/Introduction", "Learn/JavaScript/Client-side_web_APIs/Fetching_data", "Learn/JavaScript/Client-side_web_APIs")}}</div>
+
+<div>
+<h2 id="In_this_module">In this module</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction">Introduction to web APIs</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents">Manipulating documents</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data">Fetching data from the server</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Third_party_APIs">Third party APIs</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Drawing_graphics">Drawing graphics</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Video_and_audio_APIs">Video and audio APIs</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage">Client-side storage</a></li>
+</ul>
+</div>
diff --git a/files/zh-tw/learn/javascript/first_steps/a_first_splash/index.html b/files/zh-tw/learn/javascript/first_steps/a_first_splash/index.html
new file mode 100644
index 0000000000..38c7e4a4c4
--- /dev/null
+++ b/files/zh-tw/learn/javascript/first_steps/a_first_splash/index.html
@@ -0,0 +1,706 @@
+---
+title: 初次接觸Javascript
+slug: Learn/JavaScript/First_steps/A_first_splash
+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">目前你已經學會了一些JavaScript的理論,以及你能用它做些什麼。我們現在要透過一個完整的實際範例給你一個JavaScript基本功能的速成班。你將能一步一步地做出一個簡單的"猜數字"遊戲</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">先備知識:</th>
+ <td>基礎的電腦知識 , 有基礎的 HTML 跟 CSS 知識 ,<br>
+ 還有知道 JavaScript 是甚麼 .</td>
+ </tr>
+ <tr>
+ <th scope="row">目標:</th>
+ <td>獲得第一次寫 JavaScript 的經驗 ,<br>
+ 還有知道最基礎的 JavaScript 程式該怎麼寫 .</td>
+ </tr>
+ </tbody>
+</table>
+
+<p>並不會要求你馬上就能仔細地了解所有程式碼 — 目前我們只是想介紹一些概觀,並向你介紹一些關於JavaScript(以及其他程式語言)如何運作的知識。在接下來的章節你將會更仔細地瞭解這些功能!</p>
+
+<div class="note">
+<p>Note: 你會在 JavaScript 看到許多跟其他程式語言一樣的特徵 — functions , loops 之類的 ,雖然程式語法看起來有差 ,但概念大部分都差不多 .</p>
+</div>
+
+<h2 id="像程式工程師一樣思考">像程式工程師一樣思考</h2>
+
+<p>寫程式中最困難的事情之一,不是您需要學習的語法,而是如何應用它來解決現實世界中的問題。 您需要開始像個程式設計師一樣思考 — 這通常與檢視程式目標的說明有關,並確定實現這些功能所需的程式碼,以及如何使它們協同工作。</p>
+
+<p>這需要辛勤工作,程式語法經驗和練習 — 以及一點創造力。 你寫了越多程式碼,你就會越熟練。 我們不能保證你會在5分鐘內開發出“程式設計師的大腦”,但我們會給你很多機會在整個課程中練習"像程式設計師一樣思考"。</p>
+
+<p>考慮到這一點,讓我們看一下我們將在本文中構建的範例,並審視將其分解為具體任務的大致流程。</p>
+
+<h2 id="範例_—_猜數字遊戲">範例 — 猜數字遊戲</h2>
+
+<p>在本文中,我們將向您展示如何構建您可以在下面看到的簡單遊戲:</p>
+
+<div class="hidden">
+<h6 id="Top_hidden_code">Top hidden code</h6>
+
+<pre class="brush: html notranslate">&lt;!DOCTYPE html&gt;
+&lt;html&gt;
+
+&lt;head&gt;
+ &lt;meta charset="utf-8"&gt;
+ &lt;title&gt;Number guessing game&lt;/title&gt;
+ &lt;style&gt;
+ html {
+ font-family: sans-serif;
+ }
+
+ body {
+ width: 50%;
+ max-width: 800px;
+ min-width: 480px;
+ margin: 0 auto;
+ }
+
+ .lastResult {
+ color: white;
+ padding: 3px;
+ }
+ &lt;/style&gt;
+&lt;/head&gt;
+
+&lt;body&gt;
+
+ &lt;h1&gt;Number guessing game&lt;/h1&gt;
+ &lt;p&gt;We have selected a random number between 1 and 100. See if you can guess it in 10 turns or fewer. We'll tell you if your guess was too high or too low.&lt;/p&gt;
+ &lt;div class="form"&gt; &lt;label for="guessField"&gt;Enter a guess: &lt;/label&gt;&lt;input type="text" id="guessField" class="guessField"&gt; &lt;input type="submit" value="Submit guess" class="guessSubmit"&gt; &lt;/div&gt;
+ &lt;div class="resultParas"&gt;
+ &lt;p class="guesses"&gt;&lt;/p&gt;
+ &lt;p class="lastResult"&gt;&lt;/p&gt;
+ &lt;p class="lowOrHi"&gt;&lt;/p&gt;
+ &lt;/div&gt;
+
+&lt;script&gt;
+ // Your JavaScript goes here
+ 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 = '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!!!';
+ lowOrHi.textContent = '';
+ setGameOver();
+ } else {
+ lastResult.textContent = 'Wrong!';
+ lastResult.style.backgroundColor = 'red';
+ if(userGuess &lt; randomNumber) {
+ lowOrHi.textContent='Last guess was too low!' ;
+ } else if(userGuess &gt; randomNumber) {
+ lowOrHi.textContent = 'Last guess was too high!';
+ }
+ }
+
+ guessCount++;
+ guessField.value = '';
+ }
+
+ guessSubmit.addEventListener('click', checkGuess);
+
+ 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);
+ }
+
+ function resetGame() {
+ guessCount = 1;
+ const resetParas = document.querySelectorAll('.resultParas p');
+ for(let i = 0 ; i &lt; 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;
+ }
+&lt;/script&gt;
+
+&lt;/body&gt;
+&lt;/html&gt;</pre>
+</div>
+
+<p>{{ EmbedLiveSample('Top_hidden_code', '100%', 320, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<p>好好玩一下遊戲再繼續吧 —— 在繼續前先與這個遊戲熟悉起來。</p>
+
+<p>讓我們假設你的老闆給了你以下關於創建這個遊戲的簡介:</p>
+
+<blockquote>
+<p>我要你幫我做一個很簡單的猜數字遊戲 .<br>
+ 玩家要在 10 回合內猜中一個1到100之間的隨機數字 ,<br>
+ 每回合結束時都要告訴玩家他們猜對還是猜錯 ,<br>
+ 然後要是他們猜錯 , 要告訴他們數字猜的太小還是太大 ,<br>
+ 這個遊戲會在玩家猜對 , 或是猜超過 10 次時結束 ,<br>
+ 且遊戲結束時 , 要提供一個選項讓玩家可以再玩一次 .</p>
+</blockquote>
+
+<p>當看到上面的介紹後,我們可以做的第一件事就是開始拆解,盡可能的像個程式設計師,將它拆解為簡單可執行的任務:</p>
+
+<ol>
+ <li>產生一個1到100間的隨機數字。</li>
+ <li>從一開始,紀錄玩家目前回合數。</li>
+ <li>提供玩家猜數字的方向(太大還是太小)。</li>
+ <li>當玩家送出第一個猜測後,將猜測記錄下來,讓玩家可以看到他們之前的猜測。</li>
+ <li>接著檢查數字是否猜中。</li>
+ <li>如果數字猜對:
+ <ol>
+ <li>顯示恭喜訊息。</li>
+ <li>使玩家不能再輸入更多猜測(避免把遊戲玩壞)。</li>
+ <li>顯示控制鈕讓玩家可以重新開始遊戲。</li>
+ </ol>
+ </li>
+ <li>如果數字猜錯而且玩家有剩餘回合數:
+ <ol>
+ <li>告訴玩家他猜錯了。</li>
+ <li>讓玩家輸入其他的猜測</li>
+ <li>回合數增加1。</li>
+ </ol>
+ </li>
+ <li>如果數字猜錯而且玩家沒有剩餘回合數:
+ <ol>
+ <li>告訴玩家遊戲結束。</li>
+ <li>使玩家不能再輸入更多猜測(避免把遊戲玩壞)。</li>
+ <li>顯示控制鈕讓玩家可以重新開始遊戲。</li>
+ </ol>
+ </li>
+ <li>當遊戲重新開始,確保遊戲邏輯和畫面(UI,使用這介面)全面重設,然後回到第一步。</li>
+</ol>
+
+<p>現在,讓我們繼續向前,一路上我們檢視如何將這些步驟轉化為程式碼、建構出上面的範例與探索JavaScript的功能。</p>
+
+<h3 id="初步設定">初步設定</h3>
+
+<p>在課程開始前,我們希望你可以複製一份<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>)。用瀏覽器與文字編輯器將檔案打開時,你會看到簡單的標題、說明段落還有輸入猜測的表單,然而表單目前還不會做任何事情。</p>
+
+<p>所有的程式碼都會放入置於HTML底部的{{htmlelement("script")}}元素裡:</p>
+
+<pre class="brush: html notranslate">&lt;script&gt;
+
+ // Your JavaScript goes here
+
+&lt;/script&gt;
+</pre>
+
+<h3 id="加入變數儲存我們的資料">加入變數儲存我們的資料</h3>
+
+<p>我們一起開始吧。首先,在你的{{htmlelement("script")}} 元素裡加入以下幾行:</p>
+
+<pre class="brush: js notranslate">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>這一區塊的程式碼設定我們的程式中用來儲存資料的變數。簡單的來說,「變數」是「值」的容器(值可以是數字、一串文字或是其他東西)。你可以用「關鍵字」(keyword) <code>let</code>(或是<code>var</code>)後面加上變數的名字來建立變數(在<a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/First_steps/Variables#The_difference_between_var_and_let">之後的文章</a>你會看到兩者的差別)。利用關鍵字 <code>const</code> 建立常數,常數(Constant)是用來儲存你不會更改的值。我們用常數儲存使用者介面的參照,使用者介面中的文字可能會改變,但是參照所指的HTML元素的不會改變。</p>
+
+<p>藉由等於符號(<code>=</code>)後面加上一個值,你可以指定變數或是常數的值。</p>
+
+<p>在我們的範例中:</p>
+
+<ul>
+ <li>第一個變數 — <code>randomNumber</code> — 被指定成一個由數學運算的1到100間的隨機數字</li>
+ <li>接著的三個常數,分別儲存HTML中結果段落的參照,在後面的程式碼中,參照被用來插入一些數值 (注意他們都位於一個{{htmlelement("div")}}元素裡,後者在之後我們重置遊戲時會被用來選取所有三個{{htmlelement("p")}}元素):
+ <pre class="brush: html notranslate">&lt;div class="resultParas"&gt;
+ &lt;p class="guesses"&gt;&lt;/p&gt;
+ &lt;p class="lastResult"&gt;&lt;/p&gt;
+ &lt;p class="lowOrHi"&gt;&lt;/p&gt;
+&lt;/div&gt;
+</pre>
+ </li>
+ <li>接著的兩個常數,分別儲存表單中的文字輸入和送出按鈕,之後會用來控制送出玩家猜測的數字。
+ <pre class="brush: html notranslate">&lt;label for="guessField"&gt;Enter a guess: &lt;/label&gt;&lt;input type="text" id="guessField" class="guessField"&gt;
+&lt;input type="submit" value="Submit guess" class="guessSubmit"&gt;</pre>
+ </li>
+ <li>最後兩個變數,一個儲存回合數1,另一個儲存指向重新開始按鈕的參照 (按鈕現在還不存在,之後會加上的)。</li>
+</ul>
+
+<div class="note">
+<p><strong>Note</strong>: 從<a href="https://developer.mozilla.org/en-US/docs/user:chrisdavidmills/variables">下一篇文章</a>開始,你會學到更多有關變數的事。</p>
+</div>
+
+<h3 id="函式">函式</h3>
+
+<p>下一步,將下面這段添加到之前寫的那段程式碼:</p>
+
+<pre class="brush: js notranslate">function checkGuess() {
+ alert('I am a placeholder');
+}</pre>
+
+<p>函式是一段可重複利用的程式碼塊。建立一個函式便可以反複運行並避免撰寫重複的程式碼。定義函式有很多方法,在此我們先專注在一種簡單的方式。這裡我們以關鍵字 <code>function</code> 、自訂的函式名、一對括號以及一對花括號(<code>{ }</code>)建立函式。花括號中的程式碼便是我們調用函式時所要實際執行的程式碼。</p>
+
+<p>輸入函式名稱與括號便可以執行函式。</p>
+
+<p>讓我們來試試吧。儲存你的程式碼並重新整理瀏覽器畫面。進入 <a href="/zh-TW/docs/Learn/Common_questions/What_are_browser_developer_tools">開發者工具 JavaScript console</a>, 並輸入下面這行:</p>
+
+<pre class="brush: js notranslate">checkGuess();</pre>
+
+<p> 當按下 <kbd>Return</kbd>/<kbd>Enter</kbd> 時,你會看到一個警告跳窗顯示「I am a placeholder」。我們已經在程式中定義好一個函式,只要我們調用這個函式,函式便會彈出一個警告視窗。</p>
+
+<div class="note">
+<p><strong>Note</strong>: 你會在後續的課程中學習到更多關於函式的事。</p>
+</div>
+
+<h3 id="運算子">運算子</h3>
+
+<p>JavaScript 運算子可以讓我們執行比較、數學運算、連接字符串等。</p>
+
+<p>儲存我們的程式碼並重整頁面,開啟 <a href="/zh-TW/docs/Learn/Common_questions/What_are_browser_developer_tools">開發者工具 JavaScript console</a> 。接下來你可以試著輸入以下的範例 —— 輸入跟每個「範例」欄位中一樣的內容,每輸入一個就按下<kbd>Return</kbd> / <kbd>Enter</kbd>, 接著看看回傳的結果。</p>
+
+<p>如果你不能快速打開瀏覽器開發工具, 你可以使用内嵌的應用程式中輸入以下範例:</p>
+
+<div class="hidden">
+<h6 id="Hidden_code">Hidden code</h6>
+
+<pre class="brush: html notranslate">&lt;!DOCTYPE html&gt;
+&lt;html&gt;
+ &lt;head&gt;
+ &lt;meta charset="utf-8"&gt;
+ &lt;title&gt;JavaScript console&lt;/title&gt;
+ &lt;style&gt;
+ * {
+ 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;
+ }
+
+ &lt;/style&gt;
+ &lt;/head&gt;
+ &lt;body&gt;
+
+
+ &lt;/body&gt;
+
+ &lt;script&gt;
+ 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 = '&gt;';
+ inputDiv.appendChild(inputPara);
+ inputDiv.appendChild(inputForm);
+ document.body.appendChild(inputDiv);
+ inputDiv.focus();
+
+ if(document.querySelectorAll('div').length &gt; 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();
+
+ &lt;/script&gt;
+&lt;/html&gt;</pre>
+</div>
+
+<p>{{ EmbedLiveSample('Hidden_code', '100%', 300, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<p>首先讓我們看看以下的算數運算子:</p>
+
+<table class="standard-table">
+ <thead>
+ <tr>
+ <th scope="col">運算子</th>
+ <th scope="col">名稱</th>
+ <th scope="col">範例</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>+</code></td>
+ <td>加法</td>
+ <td><code>6 + 9</code></td>
+ </tr>
+ <tr>
+ <td><code>-</code></td>
+ <td>減法</td>
+ <td><code>20 - 15</code></td>
+ </tr>
+ <tr>
+ <td><code>*</code></td>
+ <td>乘法</td>
+ <td><code>3 * 7</code></td>
+ </tr>
+ <tr>
+ <td><code>/</code></td>
+ <td>除法</td>
+ <td><code>10 / 5</code></td>
+ </tr>
+ </tbody>
+</table>
+
+<p>你也可以使用 <code>+</code> 來連接字串 (在程式設計中,這稱爲<strong>連接</strong>)。試著輸入以下幾行程式,每次一行:</p>
+
+<pre class="brush: js notranslate">var name = 'Bingo';
+name;
+var hello = ' says hello!';
+hello;
+var greeting = name + hello;
+greeting;</pre>
+
+<p>你也可以使用一些捷徑,這些被稱爲增量賦值運算子。如果你只是簡單想將兩個字串加在一起,你可以這樣做:</p>
+
+<pre class="brush: js notranslate">name += ' says hello!';</pre>
+
+<p>相當於</p>
+
+<pre class="brush: js notranslate">name = name + ' says hello!';</pre>
+
+<p>當我們進行真假值測試時 (例如{{anch("條件", "下面")}}),我們可以使用比較運算子,如:</p>
+
+<table class="standard-table">
+ <thead>
+ <tr>
+ <th scope="col">運算子</th>
+ <th scope="col">名稱</th>
+ <th scope="col">範例</th>
+ </tr>
+ <tr>
+ <td><code>===</code></td>
+ <td>嚴格等於 (是否完全一樣?)</td>
+ <td><code>5 === 2 + 4</code></td>
+ </tr>
+ <tr>
+ <td><code>!==</code></td>
+ <td>不等於 (是否不一樣?)</td>
+ <td><code>'Chris' !== 'Ch' + 'ris'</code></td>
+ </tr>
+ <tr>
+ <td><code>&lt;</code></td>
+ <td>小於</td>
+ <td><code>10 &lt; 6</code></td>
+ </tr>
+ <tr>
+ <td><code>&gt;</code></td>
+ <td>大於</td>
+ <td><code>10 &gt; 20</code></td>
+ </tr>
+ </thead>
+</table>
+
+<h3 id="條件">條件</h3>
+
+<p>回到 <code>checkGuess()</code> 函式,我們希望的結果當然不只是彈出簡單訊息而已。我們更想要知道這個函式將如何檢查玩家的猜測是否準確,並回傳正確的結果。</p>
+
+<p>所以現在將 <code>checkGuess()</code> 函式替換成下面這個版本:</p>
+
+<pre class="brush: js notranslate">function checkGuess() {
+ var 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 &lt; randomNumber) {
+ lowOrHi.textContent = 'Last guess was too low!';
+ } else if(userGuess &gt; randomNumber) {
+ lowOrHi.textContent = 'Last guess was too high!';
+ }
+ }
+
+ guessCount++;
+ guessField.value = '';
+ guessField.focus();
+}</pre>
+
+<p>哇,突然出現了很多程式碼!我們來完整地看一遍這些程式並介紹它們是如何運行的。</p>
+
+<ul>
+ <li>第一行(上面的第2行)宣告一個名為 <code>userGuess</code> 的變數,並將其值設置為在表單中文字輸入格內的當前值。我們還通過內建的 <code>Number()</code> 方法運行此值,以確保該值絕對是一個數字。</li>
+ <li>接下來,我們遇到第一個條件程式碼區塊(上面的第3-5行)。條件程式碼區塊允許您能基於某個條件是否為真來選擇性地執行程式碼。它看起來有點像函式,但其實並非如此。最簡單的條件區塊格式從 <code>if</code> 關鍵字開始,然後是一些括號,然後是一些花括號。在括號內包含一個比較測試。如果括號內的比較測試回傳 <code>true</code>,花括號內的程式碼則會被執行;否則不會執行,而會繼續執行接下來的程式碼。在這個情況下,我們的比較測試是檢查 <code>guessCount</code> 變數是否等於 <code>1</code>(即,這是否為玩家的第一次嘗試):
+ <pre class="notranslate"><code>guessCount === 1</code></pre>
+ 如果是,我們將 <code>guesses</code> 段落的文字內容設為 “Previous guesses: ”。</li>
+ <li>第6行將當前 <code>userGuess</code> 的值附加到 <code>guesses</code> 段落的尾端,並加上一個空格,讓顯示的每次猜測紀錄之間都有一個空格。</li>
+ <li>下一個條件區塊(上面第8-24行)做了一些檢查:
+ <ul>
+ <li>第一個 <code>if(){ }</code> 檢查用戶的猜測是否等於<code>我們</code>JavaScript頂部設置的 <code>randomNumber</code>。如果是,代表玩家猜對了,贏了遊戲,所以我們向玩家顯示一個漂亮的綠色祝賀訊息,清除 <code>lowOrHigh</code> 段落的內容,並運行一個叫做 <code>setGameOver()</code> 的函式,這個函式我們稍後再討論。</li>
+ <li>現在我們使用 <code>else if(){ }</code> 區塊將另一個測試連接到上一個測試的後面。這個測試檢查本次猜測是否為玩家的最後一次猜測機會。如果是,則執行與上一個條件區塊相同的操作,只是這次是遊戲結束訊息,漂亮的綠色祝賀訊息。</li>
+ <li>連接到此條件區塊後面的最後一個區塊(<code>else { }</code>)只會在其他兩個測試都沒有返回 <code>true</code> 時執行(即,玩家沒有猜對,但他們還有更多的猜測機會)。在這種情況下,我們告訴他們猜錯了,然後我們執行另一個條件測試以檢查猜測是高於還是低於正確答案 <code>randomNumber</code>,並顯示進一步的訊息來告訴他們要猜得更高或更低。</li>
+ </ul>
+ </li>
+ <li>函式中的最後三行(上面的第26-28行)讓玩家可以提交下一個猜測。我們將<code>guessCount</code>變數加1,來增加玩家已使用的猜測次數(<code>++</code>是遞增操作 - 遞增1),並將表單中文字輸入格內的文字清空並給予其焦點(顯示文字輸入游標),準備好讓玩家輸入下一個猜測。</li>
+</ul>
+
+<h3 id="事件">事件</h3>
+
+<p>現在我們有了一個很好的 <code>checkGuess()</code> 函式,但它並不會做任何事情,因為我們還沒有呼叫它。我們想在按下 “Submit guess” 按鈕時呼叫它,為此,我們需要使用<strong>事件</strong>。事件是在瀏覽器中發生的操作,例如單擊按鈕,加載頁面或播放影片,以讓我們可以在這些操作發生時執行程式碼。偵聽事件發生的構造稱為<strong>事件偵聽器</strong>,偵聽事件而觸發執行的程式碼稱為<strong>事件處理器</strong>。</p>
+
+<p>在 <code>checkGuess()</code> 函式下面添加下行(不是指函式內部的後面,而是函式外):</p>
+
+<pre class="brush: js notranslate">guessSubmit.addEventListener('click', checkGuess);</pre>
+
+<p>這裡我們為 <code>guessSubmit</code> 按鈕添加一個事件偵聽器。這是一個函式,它接受兩個輸入值(稱為<em>參數</em>) - 我們正在監聽的事件類型字串(本例中的 <code>click</code>),以及我們想要在事件發生時運行的程式碼(在這種情況下是<code>checkGuess()</code>函式) — 請注意,在編寫 <a href="https://developer.mozilla.org/zh-TW/docs/Web/API/EventTarget/addEventListener" title="EventTarget.addEventListener() 方法能將指定的事件監聽器註冊到 EventTarget 實作物件上。EventTarget 可能是 Document 中的 Element 物件、Document 物件本身、Window 物件,或是其它支援事件的物件(如:XMLHttpRequest)。"><code>addEventListener()</code></a> 內部時我們不需要為函式加上括號。</p>
+
+<p>現在保存並重整頁面,現在你的範例應該可以正常執行了。現在唯一的問題是,如果你猜對了正確的答案或用完了猜測機會,那麼遊戲就會出錯,因為我們還沒有定義 <code>setGameOver()</code> — 遊戲結束後應該執行的函式。現在讓我們加上缺少的程式碼並完成範例功能。</p>
+
+<h3 id="完成遊戲功能">完成遊戲功能</h3>
+
+<p>讓我們加入 <code>setGameOver()</code> 這個函式到我們程式碼的底部並演練它。 現在,在你的 JavaScript 尾端加上這些:</p>
+
+<pre class="brush: js notranslate">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>函數中的前兩行透過將表單的文字輸入和按鈕的 <code>disabled</code> 屬性設為 <code>true</code> 來將兩者無效化。這很重要,因為如果沒有這麼做,使用者可能會在遊戲結束後繼續送出更多猜測值,這也許會把東西弄得一團糟。</li>
+ <li>接下來的三行會生成一個新的 {{htmlelement("button")}} 元素,將它的文字標籤設為「Start new game」後,添加到我們的HTML的最尾端。</li>
+ <li>最後一行則會在我們的新按鈕上設置一個事件偵聽器,來讓使用者按下按鈕時執行一個叫 <code>resetGame()</code> 的函數。</li>
+</ul>
+
+<p>現在讓我們來定義 <code>resetGame()</code>!再次將下面這些程式碼加進你的 JavaScript 的最下方。</p>
+
+<pre class="brush: js notranslate">function resetGame() {
+ guessCount = 1;
+
+ var resetParas = document.querySelectorAll('.resultParas p');
+ for (var i = 0 ; i &lt; 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>這段相對較常的程式碼會完全將所有東西重置到遊戲的初始狀態,讓玩家可以再玩一次。這段程式碼做了下面這些事:</p>
+
+<ul>
+ <li>將 <code>guessCount</code> 設回 1。</li>
+ <li>清除所有訊息段落。</li>
+ <li>將重置按鈕移除。</li>
+ <li>將表單元素有效化,清空文字輸入並給予其焦點,準備好讓玩家能夠進行新一輪的猜測。</li>
+ <li><code>將lastResult</code> 段落的背景顏色設回白色。</li>
+ <li>生成一個新的隨機數值,才不會讓玩家又猜一次重複的答案!</li>
+</ul>
+
+<p><strong>現在,你應該有了一個完整且能正常執行的簡單遊戲了 — 恭喜你啦!</strong></p>
+
+<p>接下來這篇文章的工作只剩下來談談其他幾個很重要的程式功能,你應該已經看過了,只是還沒察覺罷了。</p>
+
+<h3 id="迴圈">迴圈</h3>
+
+<p>上面的程式碼中,一個我們需要仔細看看的部份是 <a href="/zh-TW/docs/Web/JavaScript/Reference/Statements/for">for</a> 迴圈。迴圈在程式設計中是一個非常重要的內容,可以讓你在滿足條件前反覆執行同一段程式碼。</p>
+
+<p>開始吧,打開你的 <a href="/zh-TW/docs/Learn/Common_questions/What_are_browser_developer_tools">開發者工具 JavaScript console</a>,然後輸入下面這行:</p>
+
+<pre class="brush: js notranslate">for (var i = 1 ; i &lt; 21 ; i++) { console.log(i) }</pre>
+
+<p>看見了嗎?在你的主控台內印出了數字 1到 20。這就是迴圈的效果。一個 for 迴圈需要三個參數:</p>
+
+<ol>
+ <li><strong>起始動作:</strong>這個例子中我們從 1 開始累加,這個起始數值可以是任何你想要的值。你也可以不要使用 <code>i</code> 這個變數名稱,但習慣上我們會使用 <code>i</code> ,因為它簡單好記。 </li>
+ <li><strong>離開條件:</strong>這裡我們指定了 <code>i &lt; 21</code> — 這個迴圈會一直執行直到 <code>i</code> 不再小於 21。當 <code>i</code> 達到 21,這個迴圈就會停止執行。</li>
+ <li><strong>增加動作:</strong>我們指定了 <code>i++</code>,「將 <code>i</code> 的值加 1」。這個迴圈會對每個 <code>i</code> 的值執行一次,直到 <code>i</code> 達到 21(如上一條所述)。這個例子中,我們簡單的透過 {{domxref("Console.log", "console.log()")}} 將每次迴圈中 <code>i</code> 的值輸出到主控台中。</li>
+</ol>
+
+<p>現在我們來看看在猜謎遊戲中的迴圈 — 這可以在 <code>resetGame()</code> 函式中找到:</p>
+
+<pre class="brush: js notranslate">var resetParas = document.querySelectorAll('.resultParas p');
+for (var i = 0 ; i &lt; resetParas.length ; i++) {
+ resetParas[i].textContent = '';
+}</pre>
+
+<p>這段程式碼透過呼叫 {{domxref("Document.querySelectorAll", "querySelectorAll()")}} 創建一個變數並存著一個在 <code>&lt;div class="resultParas"&gt;</code> 中的所有段落清單,然後使用迴圈來遍歷每個段落元素,並移除其內容。</p>
+
+<h3 id="稍微討論一下物件">稍微討論一下物件</h3>
+
+<p>在開始討論這個段落的話題前,先來做點小小修改。在你的 JavaScript 接近頂部的 <code>var resetButton</code> 下一行加上:</p>
+
+<pre class="brush: js notranslate">guessField.focus();</pre>
+
+<p>,然後存檔。</p>
+
+<p>這一行呼叫了 {{domxref("HTMLElement.focus", "focus()")}} 方法來在頁面讀取時,將輸入游標自動放進 {{htmlelement("input")}} 文字欄裡面,這意味著使用者在開啟頁面後就可以直接使用鍵盤來在文字欄內輸入文字,而不用先點選文字欄。這只是個小修改,可是大大的提升了使用體驗,也給了使用者清楚的提示 — 提示他們要做些什麼來遊玩這個遊戲。</p>
+
+<p>讓我們來分析一下究竟發生了什麼事。在JavaScript中,所有東西都是一個<strong>物件</strong>。物件是一個集合,由許多相關的功能打包成一體。你可以創建一個你自己的物件,不過這比較進階,我們現在並不會涵蓋這個內容,這些會在課程的後期提到。現在,我們只會簡要的提到一些你的瀏覽器內建的物件,他們能夠讓你做到許多有用的事。</p>
+
+<p>在這個例子中,我們首先創建了一個 <code>guessField</code> 變數,儲存著一個指向HTML表單中文字輸入欄的參照 — 這可以在我們定義變數的區塊中找到:</p>
+
+<pre class="brush: js notranslate">var guessField = document.querySelector('.guessField');</pre>
+
+<p>我們使用了 {{domxref("document.querySelector", "querySelector()")}} 來取得這個參照,前者是 {{domxref("document")}} 物件的方法。<code>querySelector()</code> 接受一個參數 — 一個 <a href="/zh-TW/docs/Learn/CSS/Introduction_to_CSS/Selectors">CSS 選擇器</a>, 會回傳你想要的元素參照。</p>
+
+<p>因為現在 <code>guessField</code> 中存著一個指向 {{htmlelement("input")}} 元素的參照,它現在可以存取這個元素的屬性(基本上就是存在物件中的變數,其中有一些可能會是常數)和方法(基本上就是存在物件中的函式)了。文字輸入欄的其中一個方法便是 <code>focus()</code>,我們便可以透過呼叫這個方法來給予其焦點:</p>
+
+<pre class="brush: js notranslate">guessField.focus();</pre>
+
+<p>沒有存著表單元素參照的變數就不會有 <code>focus()</code> 方法能使用。<br>
+ 例如存著一個 {{htmlelement("p")}} 元素的 <code>guesses</code> 和存著一個數值的 <code>guessCount</code>。</p>
+
+<h3 id="來玩玩瀏覽器物件">來玩玩瀏覽器物件</h3>
+
+<p>讓我們來稍微玩一點瀏覽器內建的物件吧。</p>
+
+<ol>
+ <li>首先在瀏覽器中開啟你的程式。</li>
+ <li>接下來,打開你的<a href="/zh-TW/docs/Learn/Common_questions/What_are_browser_developer_tools">開發者工具 JavaScript console</a>。</li>
+ <li>輸入 <code>guessField</code>,可以看到主控台顯示這個變數儲存著一個 {{htmlelement("input")}} 元素。你還可以發現主控台會自動幫你完成已存在的物件名稱!</li>
+ <li>接下來輸入:
+ <pre class="brush: js notranslate">guessField.value = 'Hello';</pre>
+ <code>value</code> 屬性儲存著現在文字輸入欄內的內容參照。現在按下 <kbd>Enter</kbd>,看看文字欄內的內容是不是變了?</li>
+ <li>試著輸入 <code>guesses</code> 然後按下 <kbd>Enter</kbd>,主控台會顯示這個變數儲存著一個 {{htmlelement("p")}} 元素。</li>
+ <li>現在輸入:
+ <pre class="brush: js notranslate">guesses.value</pre>
+ 瀏覽器會回傳 <code>undefined</code>,因為 <code>value</code> 不存在在段落元素裡面。</li>
+ <li>要更改段落元素中的文字,你需要的是 {{domxref("Node.textContent", "textContent")}} 屬性。試試這個:
+ <pre class="brush: js notranslate">guesses.textContent = 'Where is my paragraph?';</pre>
+ </li>
+ <li>現在來做些好玩的事。一行一行輸入並 <kbd>Enter</kbd>:
+ <pre class="brush: js notranslate">guesses.style.backgroundColor = 'yellow';
+guesses.style.fontSize = '200%';
+guesses.style.padding = '10px';
+guesses.style.boxShadow = '3px 3px 6px black';</pre>
+ 每個在頁面上的元素都有一個 <code>style</code> 屬性,其本身又是另一個物件,包含著許多該元素的行內 CSS 屬性。這讓我們能透過 JavaScript 來動態的為元素設置 CSS 屬性。</li>
+</ol>
+
+<h2 id="差不多就到這了">差不多就到這了</h2>
+
+<p>這就是我們的範例 — 你順利地來到結尾了,做得不錯!試試你的最終成品,或試試<a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/first-splash/number-guessing-game.html">我們的版本</a>。如果你仍然有困難沒有解決,再看看<a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/first-splash/number-guessing-game.html">我們的原始碼</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="在這個學習模組中">在這個學習模組中</h2>
+
+<ul>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_is_JavaScript">什麼是 JavaScript?</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/A_first_splash">和 JavaScript 的第一次接觸</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_went_wrong">什麼出錯了? JavaScript 的疑難排解(除錯)</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Variables">儲存你需要的資訊 — 變數</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Math">JavaScript 的基本運算— 數字 與 運算子</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Strings">處理文字 — JavaScript 的字串</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Useful_string_methods">有用的字串方法</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Arrays">陣列</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Silly_story_generator">附錄:笑話產生器</a></li>
+</ul>
diff --git a/files/zh-tw/learn/javascript/first_steps/arrays/index.html b/files/zh-tw/learn/javascript/first_steps/arrays/index.html
new file mode 100644
index 0000000000..895183b811
--- /dev/null
+++ b/files/zh-tw/learn/javascript/first_steps/arrays/index.html
@@ -0,0 +1,571 @@
+---
+title: Arrays
+slug: Learn/JavaScript/First_steps/Arrays
+translation_of: Learn/JavaScript/First_steps/Arrays
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps/Silly_story_generator", "Learn/JavaScript/First_steps")}}</div>
+
+<p class="summary">在本單元的最後一篇文章中,我們將介紹陣列——一種在單個變數名下儲存資料項列表的簡潔方法。在這裡,我們看看為什麼這很有用,然後探討如何建立陣列,檢索、增加和刪除儲存在陣列中的項目等等。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">先備知識:</th>
+ <td>基本計算機知識、基本理解 HTML 與 CSS、知道 JavaScript 是什麼。</td>
+ </tr>
+ <tr>
+ <th scope="row">目標:</th>
+ <td>理解何謂陣列並在 JavaScript 操作之。</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="什麼是陣列?">什麼是陣列?</h2>
+
+<p>陣列通常描述為「像列表的物件」:也就是一個列表物件,裡面含有幾個數值。陣列物件能放在變數裡面,處理方式也與資料型別大致相同。不過主要差異為,陣列可以獨立存取、並高效處理裡面的數值:像是利用迴圈,對每個數值作相同處理。例如我們的陣列是一組有項目和價格的產品、我們可以用迴圈把單價印在發票上、最後在發票底下印出合計。</p>
+
+<p>不用陣列的話,就會需要註冊、並單獨呼叫很多獨立變數。這樣會花更多時間寫程式、效率更低、還更容易寫錯。只有十個的話還好解決,但如果有一百個,甚至一千個呢?我們會在接下來闡述之。</p>
+
+<p>與前幾篇文章一樣,讓我們在 JavaScript 控制台中輸入一些示例,來了解陣列的基礎知識吧。</p>
+
+<h3 id="建立陣列">建立陣列</h3>
+
+<p>陣列用方括弧包起來,每個單位會用逗號分隔起來。</p>
+
+<ol>
+ <li>來作一個購物清單的陣列吧:我們會做類似下面的事情。在主控台中輸入以下程式:
+ <pre class="brush: js notranslate">var shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];
+shopping;</pre>
+ </li>
+ <li>在此,陣列的每個單位都是字串。但請記住,陣列可以儲存任何單位:字串、數字、物件、另一個變數、甚至是另一個陣列。也可以混合單位的型別:它們不一定都要是數字或字串。來試試這個:
+ <pre class="brush: js notranslate">var sequence = [1, 1, 2, 3, 5, 8, 13];
+var random = ['tree', 795, [0, 1, 2]];</pre>
+ </li>
+ <li>看下去之前,試著自己作幾個陣列。</li>
+</ol>
+
+<h3 id="存取並修改陣列的單位">存取並修改陣列的單位</h3>
+
+<p>你可以使用括號標記法存取個別單位,同時也可以<a href="/en-US/Learn/JavaScript/First_steps/Useful_string_methods#Retrieving_a_specific_string_character">存取字串中的字母</a>。</p>
+
+<ol>
+ <li>在主控台輸入以下程式:
+ <pre class="brush: js notranslate">shopping[0];
+// returns "bread"</pre>
+ </li>
+ <li>也可以透過賦予陣列新數值修改該單位。試試這個:
+ <pre class="brush: js notranslate">shopping[0] = 'tahini';
+shopping;
+// shopping 回傳 [ "tahini", "milk", "cheese", "hummus", "noodles" ]</pre>
+
+ <div class="note"><strong>注:</strong>前面有說過,但還是提醒下:電腦從 0 開始數!</div>
+ </li>
+ <li>請注意,陣列裡面的陣列稱為多維陣列(multidimensional array)。你可以撰寫兩組方括弧,來存取陣列裡面的陣列單位。例如說,存取前述 <code>random</code> 變數內的陣列單位就可以這麼寫:
+ <pre class="brush: js notranslate">random[2][2];</pre>
+ </li>
+ <li>看下去之前,試著進一步使用並修改陣列。</li>
+</ol>
+
+<h3 id="找出陣列長度">找出陣列長度</h3>
+
+<p>找出陣列長度(意即有幾個單位在陣列內)的方法,跟找出字串長度(含有幾個字元)的方式一樣——都是使用 {{jsxref("Array.prototype.length","length")}} 屬性。試試下方程式行:</p>
+
+<pre class="brush: js notranslate">shopping.length;
+// should return 5</pre>
+
+<p>這還有其他用途,但最常見的用法是讓迴圈一直循環直到所有的單元都走過一次。 舉個例子:</p>
+
+<pre class="brush: js notranslate">var sequence = [1, 1, 2, 3, 5, 8, 13];
+for (var i = 0; i &lt; sequence.length; i++) {
+ console.log(sequence[i]);
+}</pre>
+
+<p>在後續的章節,你會學到更多關於迴圈的部分;簡而言之,上述程式碼的意思是:</p>
+
+<ol>
+ <li>從陣列中索引為 0 的單元開始循環。</li>
+ <li>當索引值等於陣列的長度時,停止循環。這個方法對任何長度的陣列都可行,但在這個例子中,迴圈會當索引等於 7 時停止循環(這樣很好,因為最後一個單元——我們希望有包含到的——是6)。</li>
+ <li>我們在瀏覽器 console 中用 <code><a href="/en-US/docs/Web/API/Console/log">console.log()</a></code> 將每個單元列印出來。</li>
+</ol>
+
+<h2 id="好用的陣列方法">好用的陣列方法</h2>
+
+<p>在這個小節中,我們會介紹一些相當有用、有關陣列的方法。例如將字串拆分為陣列,反之亦然,以及增加新的單位到陣列中。</p>
+
+<h3 id="在字串與陣列之間轉換">在字串與陣列之間轉換</h3>
+
+<p>通常你會看到一組含有原始資料的長字串,而你可能會希望將有用的單元拆分、組成更好用的形式,對他進行操作。為了達成這個目的,我們可以使用 {{jsxref("String.prototype.split()","split()")}} 方法。它最簡單的形式是只使用一個參數,你想分離的字串位置的字元(分隔符),而後它會返回陣列中在分隔符之間的子字串。</p>
+
+<div class="note">
+<p><strong>Note</strong>: 好的,在技術上它屬於字串的方法,而非陣列的方法。但因為它可以很順利地對陣列進行操作,因此我們把它列在這邊。</p>
+</div>
+
+<ol>
+ <li>來試試這個,看它如何運作。首先,建立一個字串在你的 console:
+ <pre class="brush: js notranslate">var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';</pre>
+ </li>
+ <li>現在我們用逗點來分隔字串:
+ <pre class="brush: js notranslate">var myArray = myData.split(',');
+myArray;</pre>
+ </li>
+ <li>最後,試著找出你新的陣列的長度,並且從中取出一些單元:
+ <pre class="brush: js notranslate">myArray.length;
+myArray[0]; // the first item in the array
+myArray[1]; // the second item in the array
+myArray[myArray.length-1]; // the last item in the array</pre>
+ </li>
+ <li>相對地,你也可以用 {{jsxref("Array.prototype.join()","join()")}} 方法。試試下面這段:
+ <pre class="brush: js notranslate">var myNewString = myArray.join(',');
+myNewString;</pre>
+ </li>
+ <li>另一個將陣列轉換為字串的方法是用 {{jsxref("Array.prototype.toString()","toString()")}} 。<code>toString()</code> 因為不需要參數而比 <code>join()</code> 更簡潔,但因此也更多限制。使用 <code>join()</code> 你可以使用特定的分隔符(試著使用其他不同的字元來執行步驟 4)。
+ <pre class="brush: js notranslate">var dogNames = ['Rocket','Flash','Bella','Slugger'];
+dogNames.toString(); //Rocket,Flash,Bella,Slugger</pre>
+ </li>
+</ol>
+
+<h3 id="新增與移除陣列單位">新增與移除陣列單位</h3>
+
+<p>我們還沒談到增加與移除陣列的單位,現在來看看吧!我們使用上一個小節中的 <code>myArray</code> 陣列。如果你沒跟隨到上一個小節,那就先在你的 console 建立下面這個陣列:</p>
+
+<pre class="brush: js notranslate">var myArray = ['Manchester', 'London', 'Liverpool', 'Birmingham', 'Leeds', 'Carlisle'];</pre>
+
+<p>首先,我們可以分別使用 {{jsxref("Array.prototype.push()","push()")}} 和 {{jsxref("Array.prototype.pop()","pop()")}} 來增加或移除一個在陣列最末端的單元 。</p>
+
+<ol>
+ <li>Let's use <code>push()</code> first — note that you need to include one or more items that you want to add to the end of your array. Try this:
+
+ <pre class="brush: js notranslate">myArray.push('Cardiff');
+myArray;
+myArray.push('Bradford', 'Brighton');
+myArray;
+</pre>
+ </li>
+ <li>The new length of the array is returned when the method call completes. If you wanted to store the new array length in a variable, you could do something like this:
+ <pre class="brush: js notranslate">var newLength = myArray.push('Bristol');
+myArray;
+newLength;</pre>
+ </li>
+ <li>Removing the last item from the array is as simple as running <code>pop()</code> on it. Try this:
+ <pre class="brush: js notranslate">myArray.pop();</pre>
+ </li>
+ <li>The item that was removed is returned when the method call completes. To save that item in a new variable, you could do this:
+ <pre class="brush: js notranslate">var removedItem = myArray.pop();
+myArray;
+removedItem;</pre>
+ </li>
+</ol>
+
+<p>{{jsxref("Array.prototype.unshift()","unshift()")}} and {{jsxref("Array.prototype.shift()","shift()")}} work in exactly the same way as <code>push()</code> and <code>pop()</code>, respectively, except that they work on the beginning of the array, not the end.</p>
+
+<ol>
+ <li>First <code>unshift()</code> — try the following commands:
+
+ <pre class="brush: js notranslate">myArray.unshift('Edinburgh');
+myArray;</pre>
+ </li>
+ <li>Now <code>shift()</code>; try these!
+ <pre class="brush: js notranslate">var removedItem = myArray.shift();
+myArray;
+removedItem;</pre>
+ </li>
+</ol>
+
+<h2 id="Active_learning_Printing_those_products!">Active learning: Printing those products!</h2>
+
+<p>Let's return to the example we described earlier — printing out product names and prices on an invoice, then totaling the prices and printing them at the bottom. In the editable example below there are comments containing numbers — each of these marks a place where you have to add something to the code. They are as follows:</p>
+
+<ol>
+ <li>Below the <code>// number 1</code> comment are a number of strings, each one containing a product name and price separated by a colon. We'd like you to turn this into an array and store it in an array called <code>products</code>.</li>
+ <li>On the same line as the <code>// number 2</code> comment is the beginning of a for loop. In this line we currently have <code>i &lt;= 0</code>, which is a conditional test that causes the <a href="/en-US/Learn/JavaScript/First_steps/A_first_splash#Loops">for loop</a> to stop immediately, because it is saying "stop when <code>i</code> is no longer less than or equal to 0", and <code>i</code> starts at 0. We'd like you to replace this with a conditional test that stops the loop when <code>i</code> is no longer less than the <code>products</code> array's length.</li>
+ <li>Just below the <code>// number 3</code> comment we want you to write a line of code that splits the current array item (<code>name:price</code>) into two separate items, one containing just the name and one containing just the price. If you are not sure how to do this, consult the <a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a> article for some help, or even better, look at the {{anch("Converting between strings and arrays")}} section of this article.</li>
+ <li>As part of the above line of code, you'll also want to convert the price from a string to a number. If you can't remember how to do this, check out the <a href="/en-US/Learn/JavaScript/First_steps/Strings#Numbers_versus_strings">first strings article</a>.</li>
+ <li>There is a variable called <code>total</code> that is created and given a value of 0 at the top of the code. Inside the loop (below <code>// number 4</code>) we want you to add a line that adds the current item price to that total in each iteration of the loop, so that at the end of the code the correct total is printed onto the invoice. You might need an <a href="/en-US/Learn/JavaScript/First_steps/Math#Assignment_operators">assignment operator</a> to do this.</li>
+ <li>We want you to change the line just below <code>// number 5</code> so that the <code>itemText</code> variable is made equal to "current item name — $current item price", for example "Shoes — $23.99" in each case, so the correct information for each item is printed on the invoice. This is just simple string concatenation, which should be familiar to you.</li>
+</ol>
+
+<div class="hidden">
+<h6 id="Playable_code">Playable code</h6>
+
+<pre class="brush: html notranslate">&lt;h2&gt;Live output&lt;/h2&gt;
+
+&lt;div class="output" style="min-height: 150px;"&gt;
+
+&lt;ul&gt;
+
+&lt;/ul&gt;
+
+&lt;p&gt;&lt;/p&gt;
+
+&lt;/div&gt;
+
+&lt;h2&gt;Editable code&lt;/h2&gt;
+
+&lt;p class="a11y-label"&gt;Press Esc to move focus away from the code area (Tab inserts a tab character).&lt;/p&gt;
+
+&lt;textarea id="code" class="playable-code" style="height: 410px;width: 95%"&gt;
+var list = document.querySelector('.output ul');
+var totalBox = document.querySelector('.output p');
+var total = 0;
+list.innerHTML = '';
+totalBox.textContent = '';
+// number 1
+ 'Underpants:6.99'
+ 'Socks:5.99'
+ 'T-shirt:14.99'
+ 'Trousers:31.99'
+ 'Shoes:23.99';
+
+for (var i = 0; i &lt;= 0; i++) { // number 2
+ // number 3
+
+ // number 4
+
+ // number 5
+ itemText = 0;
+
+ var listItem = document.createElement('li');
+ listItem.textContent = itemText;
+ list.appendChild(listItem);
+}
+
+totalBox.textContent = 'Total: $' + total.toFixed(2);
+&lt;/textarea&gt;
+
+&lt;div class="playable-buttons"&gt;
+ &lt;input id="reset" type="button" value="Reset"&gt;
+ &lt;input id="solution" type="button" value="Show solution"&gt;
+&lt;/div&gt;
+</pre>
+
+<pre class="brush: js notranslate">var textarea = document.getElementById('code');
+var reset = document.getElementById('reset');
+var solution = document.getElementById('solution');
+var code = textarea.value;
+var 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();
+});
+
+var jsSolution = 'var list = document.querySelector(\'.output ul\');\nvar totalBox = document.querySelector(\'.output p\');\nvar total = 0;\nlist.innerHTML = \'\';\ntotalBox.textContent = \'\';\n\nvar products = [\'Underpants:6.99\',\n \'Socks:5.99\',\n \'T-shirt:14.99\',\n \'Trousers:31.99\',\n \'Shoes:23.99\'];\n\nfor(var i = 0; i &lt; products.length; i++) {\n var subArray = products[i].split(\':\');\n var name = subArray[0];\n var price = Number(subArray[1]);\n total += price;\n itemText = name + \' — $\' + price;\n\n var listItem = document.createElement(\'li\');\n listItem.textContent = itemText;\n list.appendChild(listItem);\n}\n\ntotalBox.textContent = \'Total: $\' + total.toFixed(2);';
+var 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) {
+ var scrollPos = textarea.scrollTop;
+ var caretPos = textarea.selectionStart;
+
+ var front = (textarea.value).substring(0, caretPos);
+ var 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>
+
+
+
+<pre class="brush: css notranslate">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-color: #f5f9fa;
+}</pre>
+</div>
+
+<p>{{ EmbedLiveSample('Playable_code', '100%', 730, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<h2 id="Active_learning_Top_5_searches">Active learning: Top 5 searches</h2>
+
+<p>A good use for array methods like {{jsxref("Array.prototype.push()","push()")}} and {{jsxref("Array.prototype.pop()","pop()")}} is when you are maintaining a record of currently active items in a web app. In an animated scene for example, you might have an array of objects representing the background graphics currently displayed, and you might only want 50 displayed at once, for performance or clutter reasons. As new objects are created and added to the array, older ones can be deleted from the array to maintain the desired number.</p>
+
+<p>In this example we're going to show a much simpler use — here we're giving you a fake search site, with a search box. The idea is that when terms are entered in the search box, the top 5 previous search terms are displayed in the list. When the number of terms goes over 5, the last term starts being deleted each time a new term is added to the top, so the 5 previous terms are always displayed.</p>
+
+<div class="note">
+<p><strong>Note</strong>: In a real search app, you'd probably be able to click the previous search terms to return to previous searches, and it would display actual search results! We are just keeping it simple for now.</p>
+</div>
+
+<p>To complete the app, we need you to:</p>
+
+<ol>
+ <li>Add a line below the <code>// number 1</code> comment that adds the current value entered into the search input to the start of the array. This can be retrieved using <code>searchInput.value</code>.</li>
+ <li>Add a line below the <code>// number 2</code> comment that removes the value currently at the end of the array.</li>
+</ol>
+
+<div class="hidden">
+<h6 id="Playable_code_2">Playable code 2</h6>
+
+<pre class="brush: html notranslate">&lt;h2&gt;Live output&lt;/h2&gt;
+&lt;div class="output" style="min-height: 150px;"&gt;
+
+&lt;input type="text"&gt;&lt;button&gt;Search&lt;/button&gt;
+
+&lt;ul&gt;
+
+&lt;/ul&gt;
+
+&lt;/div&gt;
+
+&lt;h2&gt;Editable code&lt;/h2&gt;
+
+&lt;p class="a11y-label"&gt;Press Esc to move focus away from the code area (Tab inserts a tab character).&lt;/p&gt;
+
+
+&lt;textarea id="code" class="playable-code" style="height: 370px; width: 95%"&gt;
+var list = document.querySelector('.output ul');
+var searchInput = document.querySelector('.output input');
+var searchBtn = document.querySelector('.output button');
+
+list.innerHTML = '';
+
+var myHistory = [];
+
+searchBtn.onclick = function() {
+ // we will only allow a term to be entered if the search input isn't empty
+ if (searchInput.value !== '') {
+ // number 1
+
+ // empty the list so that we don't display duplicate entries
+ // the display is regenerated every time a search term is entered.
+ list.innerHTML = '';
+
+ // loop through the array, and display all the search terms in the list
+ for (var i = 0; i &lt; myHistory.length; i++) {
+ itemText = myHistory[i];
+ var listItem = document.createElement('li');
+ listItem.textContent = itemText;
+ list.appendChild(listItem);
+ }
+
+ // If the array length is 5 or more, remove the oldest search term
+ if (myHistory.length &gt;= 5) {
+ // number 2
+
+ }
+
+ // empty the search input and focus it, ready for the next term to be entered
+ searchInput.value = '';
+ searchInput.focus();
+ }
+}
+&lt;/textarea&gt;
+
+&lt;div class="playable-buttons"&gt;
+ &lt;input id="reset" type="button" value="Reset"&gt;
+ &lt;input id="solution" type="button" value="Show solution"&gt;
+&lt;/div&gt;</pre>
+
+
+
+
+
+<pre class="brush: css notranslate">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 notranslate">var textarea = document.getElementById('code');
+var reset = document.getElementById('reset');
+var solution = document.getElementById('solution');
+var code = textarea.value;
+var 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();
+});
+
+var jsSolution = 'var list = document.querySelector(\'.output ul\');\nvar searchInput = document.querySelector(\'.output input\');\nvar searchBtn = document.querySelector(\'.output button\');\n\nlist.innerHTML = \'\';\n\nvar myHistory= [];\n\nsearchBtn.onclick = function() {\n if(searchInput.value !== \'\') {\n myHistory.unshift(searchInput.value);\n\n list.innerHTML = \'\';\n\n for(var i = 0; i &lt; myHistory.length; i++) {\n itemText = myHistory[i];\n var listItem = document.createElement(\'li\');\n listItem.textContent = itemText;\n list.appendChild(listItem);\n }\n\n if(myHistory.length &gt;= 5) {\n myHistory.pop();\n }\n\n searchInput.value = \'\';\n searchInput.focus();\n }\n}';
+var 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) {
+ var scrollPos = textarea.scrollTop;
+ var caretPos = textarea.selectionStart;
+
+ var front = (textarea.value).substring(0, caretPos);
+ var 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%', 700, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<h2 id="Conclusion">Conclusion</h2>
+
+<p>After reading through this article, we are sure you will agree that arrays seem pretty darn useful; you'll see them crop up everywhere in JavaScript, often in association with loops in order to do the same thing to every item in an array. We'll be teaching you all the useful basics there are to know about loops in the next module, but for now you should give yourself a clap and take a well-deserved break; you've worked through all the articles in this module!</p>
+
+<p>The only thing left to do is work through this module's assessment, which will test your understanding of the articles that came before it.</p>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections">Indexed collections</a> — an advanced level guide to arrays and their cousins, typed arrays.</li>
+ <li>{{jsxref("Array")}} — the <code>Array</code> object reference page — for a detailed reference guide to the features discussed in this page, and many more.</li>
+</ul>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps/Silly_story_generator", "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/zh-tw/learn/javascript/first_steps/index.html b/files/zh-tw/learn/javascript/first_steps/index.html
new file mode 100644
index 0000000000..418325ca8f
--- /dev/null
+++ b/files/zh-tw/learn/javascript/first_steps/index.html
@@ -0,0 +1,71 @@
+---
+title: JavaScript 初探
+slug: Learn/JavaScript/First_steps
+tags:
+ - JavaScript
+ - 初學者
+ - 字串
+ - 指引
+ - 撰寫程式
+ - 數值
+ - 數學
+ - 文章
+ - 變數
+ - 運算子
+ - 陣列
+translation_of: Learn/JavaScript/First_steps
+---
+<div>{{LearnSidebar}}</div>
+
+<p class="summary">帶領各位開始體驗撰寫 JavaScript 前,在第一個 JavaScript 單元中,我們首先來回答一些基本的問題,像是「什麼是 JavaScript 啊?」、「它長什麼樣子?」以及「它能拿來做什麼?」。之後我們會詳細討論幾個關鍵元素,諸如變量(variables)、字串(strings)、數字(numbers)和陣列(arrays)。</p>
+
+<h2 id="事前準備">事前準備</h2>
+
+<p>在開始這個教學之前,你不需要具備任何的 JavaScript 相關知識,但是你應該對 HTML 及 CSS 有一點熟悉。建議你在開始學習 JavaScript 前,先看過下列內容 :</p>
+
+<ul>
+ <li><a href="/zh-TW/docs/Learn/Getting_started_with_the_web">開始使用 Web </a> (包括 <a href="/zh-TW/docs/Learn/Getting_started_with_the_web/JavaScript_basics">JavaScript 基礎簡介</a>).</li>
+ <li><a href="/zh-TW/docs/Learn/HTML/Introduction_to_HTML">HTML 簡介</a>.</li>
+ <li><a href="/zh-TW/docs/Learn/CSS/Introduction_to_CSS">CSS 簡介</a>.</li>
+</ul>
+
+<div class="note">
+<p><span style="font-size: 14px;"><strong>注意</strong></span>: 假如你正在使用 電腦/平板/其他裝置,你還不需要知道如何建立自己的檔案,你可以在線上程式撰寫系統來嘗試範例程式,像是 <a href="http://jsbin.com/">JSBin</a> 或 <a href="https://thimble.mozilla.org/">Thimble</a>.</p>
+</div>
+
+<h2 id="概觀">概觀</h2>
+
+<dl>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_is_JavaScript">什麼是 JavaScript?</a></dt>
+ <dd>歡迎來到 MDN JavaScript 新手村教學!在第一個章節中我們將一個較高的層次看 JavaScript,回答像是「它是什麼?」、「有什麼用?」之類的問題,並且確保你能了解 JavaScript 的目的。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/First_steps/A_first_splash">和 JavaScript 的第一次接觸</a></dt>
+ <dd>現在你已經學到一些關於 JavaScript 的原理,以及可以用它來作什麼,我們將經由完整的引導,給你一個關於 JavaScript 基礎功能的速成課。這裡你將會一步一步地建立一個簡單的「猜數字」遊戲。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_went_wrong">什麼出錯了? JavaScript 的疑難排解(除錯)</a></dt>
+ <dd>當你在前一章節建立的「猜數字」遊戲過程中,你可能會發現它不能運作。不要慌,這個章節的目的是提供一些提示,用來找出及修正在 JavaScript 程式裡的錯誤,讓你不會因為這些問題而煩惱。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Variables">儲存你需要的資訊 — 變數</a></dt>
+ <dd>在讀過前面幾個章節後,你現在應該能由較高的層次了解 JavaScript 是什麼,它能為你做些什麼,如何與其他的網站技術一起使用,以及它的主要的特性。在本章節中,我們將深入探討真正的基礎知識,看看 JavaScript 最基本的組成 — 變數(Variables)是如何運作 。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Math">JavaScript 的基本運算— 數字 與 運算子</a></dt>
+ <dd>本章的重點,我們討論 JavaScript 的數值計算 — 我們如何依我們的要求組合運算子與其它元素來操控數值。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Strings">處理文字 — JavaScript 的字串</a></dt>
+ <dd>接下來我們將焦點轉到字串(strings) — 這是程式裡對一段文字的稱呼。這個章節我們將會檢視學習 JavaScript 中,所有你通常想要知道於字串事情,例如創建字串、字串跳脫(escaping)操作,以及把它們組合起來。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Useful_string_methods">有用的字串方法</a></dt>
+ <dd>我們已經看過了字串的基礎知識,現在讓我們加快腳步,看看可以使用內建的方法對字串進行哪些有用的操作 ,例如:取得字串的長度、串接或分割字串、替換字串中的某個字……等等。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Arrays">陣列</a></dt>
+ <dd>在這個單元的最後一個章節,我們來看看陣列 (Array) — 把一連串資料整齊地儲存在一個變數中。我們會看到為什麼它有用,然後探索如何創建一個陣列,對陣列內的項目進行檢索、新增、刪除……等操作。</dd>
+</dl>
+
+<h2 id="測試一下">測試一下</h2>
+
+<p>下面的任務會測試你對於前面提到的 JavaScript 基本概念是否了解。</p>
+
+<dl>
+ <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/First_steps/Silly_story_generator">傻故事產生器</a></dt>
+ <dd>本次測試中,你的任務是使用在這個單元所學到的知識,建立一個能隨機產生笑話的有趣程式。祝你愉快!</dd>
+</dl>
+
+<h2 id="參考資源">參考資源</h2>
+
+<dl>
+ <dt><a class="external" href="https://learnjavascript.online/" rel="noopener">Learn JavaScript</a></dt>
+ <dd>對於想成為網站開發者一個很好的資源,以互動的方式學習 JavaScript ,包含短課程、互動測驗,自動評估狀況給予指引。前 40 堂課是免費,完整的課程可以在一次付費買下。</dd>
+</dl>
diff --git a/files/zh-tw/learn/javascript/first_steps/math/index.html b/files/zh-tw/learn/javascript/first_steps/math/index.html
new file mode 100644
index 0000000000..4c7f1d4cba
--- /dev/null
+++ b/files/zh-tw/learn/javascript/first_steps/math/index.html
@@ -0,0 +1,426 @@
+---
+title: JavaScript中的基本數學 - 數字和運算符
+slug: Learn/JavaScript/First_steps/Math
+translation_of: Learn/JavaScript/First_steps/Math
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps")}}</div>
+
+<p class="summary">在本課程的這一點上,我們將討論JavaScript中的數學 - 我們如何使用{{Glossary("Operator","operators")}} 和其他功能來成功操縱數字來進行我們的出價。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">先備知識:</th>
+ <td>電腦基礎知識,了解基本的 HTML 和 CSS ,了解 JavaScript 是什麼。</td>
+ </tr>
+ <tr>
+ <th scope="row">目標:</th>
+ <td>熟悉JavaScript中的基礎數學。</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="每個人都喜歡數學">每個人都喜歡數學</h2>
+
+<p>好吧,也許不是。 我們中的一些人喜歡數學,我們有些人討厭數學,因為我們必須在學校學習乘法和除法,而我們中的一些人兩者皆要。 但我們都不能否認數學是生活中的一個基本組成部分,我們離不開它們。 當我們學習JavaScript(或任何其他語言)的程式時,尤其如此 - 我們所做的很多事情都依賴於處理數值數據,計算新值等等,你不會驚訝學習JavaScript 有一套功能齊全的數學函數。</p>
+
+<p>本文僅討論你現在需了解的基本部分。</p>
+
+<h3 id="數字的種類">數字的種類</h3>
+
+<p><font>在程式裡,即使眾所周知的十進位數字系統也比您想像的要複雜。</font><font>我們使用不同的術語來描述不同類型的十進位數字,例如:</font></p>
+
+<ul>
+ <li><strong>Integers </strong>是整數,如:10,400,或 -5。</li>
+ <li><strong>Floating point numbers</strong> (floats) 浮點數具有小數點跟小數位,例如12.5和56.7786543。</li>
+ <li><strong>Doubles</strong> 是一種特定型態的浮點數 that have greater precision than standard floating point numbers (meaning that they are accurate to a greater number of decimal places).</li>
+</ul>
+
+<p><font>我們甚至有不同類型的號碼系統!</font><font>十進位以10為單位(表示每列使用0–9),但是也有像這些:</font></p>
+
+<ul>
+ <li><strong><font><font>二進位</font></font></strong><font><font> —計算機的最底層語言;</font><font>0和1。</font></font></li>
+ <li><strong><font><font>八進位</font></font></strong><font><font> —以8為</font>單位<font>,每列使用0–7。</font></font></li>
+ <li><strong><font><font>十六進位</font></font></strong><font><font> —以16為</font>單位<font>,在每列中使用0–9,然後使用a–f。</font></font><a href="https://translate.googleusercontent.com/translate_c?depth=1&amp;pto=aue&amp;rurl=translate.google.com.tw&amp;sl=en&amp;sp=nmt4&amp;tl=zh-TW&amp;u=https://developer.mozilla.org/en-US/Learn/CSS/Introduction_to_CSS/Values_and_units&amp;usg=ALkJrhjxtle73XLvao6e9e-CZv6u2Hq68g#Hexadecimal_values"><font><font>在CSS中</font></font></a><font><font>設置</font><a href="https://translate.googleusercontent.com/translate_c?depth=1&amp;pto=aue&amp;rurl=translate.google.com.tw&amp;sl=en&amp;sp=nmt4&amp;tl=zh-TW&amp;u=https://developer.mozilla.org/en-US/Learn/CSS/Introduction_to_CSS/Values_and_units&amp;usg=ALkJrhjxtle73XLvao6e9e-CZv6u2Hq68g#Hexadecimal_values"><font>顏色</font></a><font>之前,您可能已經遇到過這些數字</font><font>。</font></font></li>
+</ul>
+
+<p><strong><font><font>在開始擔心大腦融化之前,先等等!</font></font></strong><font><font>首先,我們將在整個課程中完全使用十進位數;您很少會想到其他類型的需求,如果有的話。</font></font> </p>
+
+<p>第二個好消息是JavaScript只有一種數字資料類型 ,猜對了!就是{{jsxref("Number")}}。這代表無論你在JavaScript需要處理哪種數字,處理方法都是一樣的。</p>
+
+<div class="note">
+<p><strong>Note</strong>: 事實上, JavaScript 有第二種數字型態, {{Glossary("BigInt")}}, 用於非常、非常、非常大的整數。但這節課我只需要擔心 <code>Number</code> 的值。</p>
+</div>
+
+<h3 id="我怎麼看都是些數字!">我怎麼看都是些數字!</h3>
+
+<p>讓我們來快速操作一些數字來重新認識一下我們會需要用到的基本語法。將下面的需求表輸入進你的開發者工具js控制台(<a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">developer tools JavaScript console</a>),或是簡單建立在任何你偏好的控制台。</p>
+
+<ol>
+ <li>首先,先來宣告兩個變數,並分別賦予他們初始值為整數與浮點數,然後接著打上變數名稱來確認萬事預備:
+ <pre class="brush: js notranslate">var myInt = 5;
+var myFloat = 6.667;
+myInt;
+myFloat;</pre>
+ </li>
+ <li>數字的值不需要引號框起來 — 試著宣告和賦予更多初始值為數字的變數,在繼續下去之前。</li>
+ <li>現在,來確認Now let's check that both our original variables are of the same datatype. There is an operator called {{jsxref("Operators/typeof", "typeof")}} in JavaScript that does this. Enter the below two lines as shown:
+ <pre class="brush: js notranslate">typeof myInt;
+typeof myFloat;</pre>
+ You should get <code>"number"</code> returned in both cases — this makes things a lot easier for us than if different numbers had different data types, and we had to deal with them in different ways. Phew!</li>
+</ol>
+
+<h2 id="算術運算符">算術運算符</h2>
+
+<p>Arithmetic operators are the basic operators that we use to do sums:</p>
+
+<table class="standard-table">
+ <thead>
+ <tr>
+ <th scope="col">Operator</th>
+ <th scope="col">Name</th>
+ <th scope="col">Purpose</th>
+ <th scope="col">Example</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>+</code></td>
+ <td>加法</td>
+ <td>Adds two numbers together.</td>
+ <td><code>6 + 9</code></td>
+ </tr>
+ <tr>
+ <td><code>-</code></td>
+ <td>減法</td>
+ <td>Subtracts the right number from the left.</td>
+ <td><code>20 - 15</code></td>
+ </tr>
+ <tr>
+ <td><code>*</code></td>
+ <td>乘法</td>
+ <td>Multiplies two numbers together.</td>
+ <td><code>3 * 7</code></td>
+ </tr>
+ <tr>
+ <td><code>/</code></td>
+ <td>除法</td>
+ <td>Divides the left number by the right.</td>
+ <td><code>10 / 5</code></td>
+ </tr>
+ <tr>
+ <td><code>%</code></td>
+ <td>餘數 (sometimes called modulo)</td>
+ <td>
+ <p>Returns the remainder left over after you've divided the left number into a number of integer portions equal to the right number.</p>
+ </td>
+ <td><code>8 % 3</code> (returns 2, as three goes into 8 twice, leaving 2 left over.)</td>
+ </tr>
+ <tr>
+ <td>**</td>
+ <td>指數</td>
+ <td>Raises a <code>base</code> number to the <code>exponent</code> power, that is, the <code>base</code> number multiplied by itself, <code>exponent</code> times. It was first Introduced in EcmaScript 2016.</td>
+ <td><code>5 ** 2</code> (5的2次方得 <code>25</code>,跟 <code>5 * 5</code>結果相同)</td>
+ </tr>
+ </tbody>
+</table>
+
+<div class="note">
+<p><strong>Note</strong>: You'll sometimes see numbers involved in sums referred to as {{Glossary("Operand", "operands")}}.</p>
+</div>
+
+<p><strong>Note</strong>: You may sometimes see exponents expressed using the older {{jsxref("Math.pow()")}} method, which works in a very similar way. For example, in <code>Math.pow(7, 3)</code>, <code>7</code> is the base and <code>3</code> is the exponent, so the result of the expression is <code>343</code>. <code>Math.pow(7, 3)</code> is equivalent to <code>7**3</code>.</p>
+
+<p>We probably don't need to teach you how to do basic math, but we would like to test your understanding of the syntax involved. Try entering the examples below into your <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">developer tools JavaScript console</a>, or use the simple built in console seen earlier if you'd prefer, to familiarize yourself with the syntax.</p>
+
+<ol>
+ <li>First try entering some simple examples of your own, such as
+ <pre class="brush: js notranslate">10 + 7
+9 * 8
+60 % 3</pre>
+ </li>
+ <li>You can also try declaring and initializing some numbers inside variables, and try using those in the sums — the variables will behave exactly like the values they hold for the purposes of the sum. For example:
+ <pre class="brush: js notranslate">var num1 = 10;
+var num2 = 50;
+9 * num1;
+num2 / num1;</pre>
+ </li>
+ <li>Last for this section, try entering some more complex expressions, such as:
+ <pre class="brush: js notranslate">5 + 10 * 3;
+num2 % 9 * num1;
+num2 + num1 / 8 + 2;</pre>
+ </li>
+</ol>
+
+<p>Some of this last set of sums might not give you quite the result you were expecting; the below section might well give the answer as to why.</p>
+
+<h3 id="Operator_precedence">Operator precedence</h3>
+
+<p>Let's look at the last example from above, assuming that <code>num2</code> holds the value 50 and <code>num1</code> holds the value 10 (as originally stated above):</p>
+
+<pre class="brush: js notranslate">num2 + num1 / 8 + 2;</pre>
+
+<p>As a human being, you may read this as <em>"50 plus 10 equals 60"</em>, then <em>"8 plus 2 equals 10"</em>, and finally <em>"60 divided by 10 equals 6"</em>.</p>
+
+<p>But the browser does <em>"10 divided by 8 equals 1.25"</em>, then <em>"50 plus 1.25 plus 2 equals 53.25"</em>.</p>
+
+<p>This is because of <strong>operator precedence</strong> — some operators will be applied before others when calculating the result of a sum (referred to as an expression, in programming).  Operator precedence in JavaScript is the same as is taught in math classes in school — Multiply and divide are always done first, then add and subtract (the sum is always evaluated from left to right).</p>
+
+<p>If you want to override operator precedence, you can put parentheses round the parts that you want to be explicitly dealt with first. So to get a result of 6, we could do this:</p>
+
+<pre class="brush: js notranslate">(num2 + num1) / (8 + 2);</pre>
+
+<p>Try it and see.</p>
+
+<div class="note">
+<p><strong>Note</strong>: A full list of all JavaScript operators and their precedence can be found in <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Operator_precedence">Expressions and operators</a>.</p>
+</div>
+
+<h2 id="遞增和遞減運算符">遞增和遞減運算符</h2>
+
+<p>Sometimes you'll want to repeatedly add or subtract one to/from a numeric variable value. This can be conveniently done using the increment (<code>++</code>) and decrement(<code>--</code>) operators. We used <code>++</code> in our  "Guess the number" game back in our <a href="/en-US/docs/Learn/JavaScript/Introduction_to_JavaScript_1/A_first_splash">first splash into JavaScript</a> article, when we added 1 to our <code>guessCount</code> variable to keep track of how many guesses the user has left after each turn.</p>
+
+<pre class="brush: js notranslate">guessCount++;</pre>
+
+<div class="note">
+<p><strong>Note</strong>: They are most commonly used in <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">loops</a>, which you'll learn about later on in the course. For example, say you wanted to loop through a list of prices, and add sales tax to each one. You'd use a loop to go through each value in turn and do the necessary calculation for adding the sales tax in each case. The incrementor is used to move to the next value when needed. We've actually provided a simple example showing how this is done — <a href="https://mdn.github.io/learning-area/javascript/introduction-to-js-1/maths/loop.html">check it out live</a>, and <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/maths/loop.html">look at the source code</a> to see if you can spot the incrementors! We'll look at loops in detail later on in the course.</p>
+</div>
+
+<p>Let's try playing with these in your console. For a start, note that you can't apply these directly to a number, which might seem strange, but we are assigning a variable a new updated value, not operating on the value itself. The following will return an error:</p>
+
+<pre class="brush: js notranslate">3++;</pre>
+
+<p>So, you can only increment an existing variable. Try this:</p>
+
+<pre class="brush: js notranslate">var num1 = 4;
+num1++;</pre>
+
+<p>Okay, strangeness number 2! When you do this, you'll see a value of 4 returned — this is because the browser returns the current value, <em>then</em> increments the variable. You can see that it's been incremented if you return the variable value again:</p>
+
+<pre class="brush: js notranslate">num1;</pre>
+
+<p>The same is true of <code>--</code> : try the following</p>
+
+<pre class="brush: js notranslate">var num2 = 6;
+num2--;
+num2;</pre>
+
+<div class="note">
+<p><strong>Note</strong>: You can make the browser do it the other way round — increment/decrement the variable <em>then</em> return the value — by putting the operator at the start of the variable instead of the end. Try the above examples again, but this time use <code>++num1</code> and <code>--num2</code>.</p>
+</div>
+
+<h2 id="賦值運算符">賦值運算符</h2>
+
+<p>Assignment operators are operators that assign a value to a variable. We have already used the most basic one, <code>=</code>, loads of times — it simply assigns the variable on the left the value stated on the right:</p>
+
+<pre class="brush: js notranslate">var x = 3; // x contains the value 3
+var y = 4; // y contains the value 4
+x = y; // x now contains the same value y contains, 4</pre>
+
+<p>But there are some more complex types, which provide useful shortcuts to keep your code neater and more efficient. The most common are listed below:</p>
+
+<table class="standard-table">
+ <thead>
+ <tr>
+ <th scope="col">Operator</th>
+ <th scope="col">Name</th>
+ <th scope="col">Purpose</th>
+ <th scope="col">Example</th>
+ <th scope="col">Shortcut for</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>+=</code></td>
+ <td>Addition assignment</td>
+ <td>Adds the value on the right to the variable value on the left, then returns the new variable value</td>
+ <td><code>x = 3;<br>
+ x += 4;</code></td>
+ <td><code>x = 3;<br>
+ x = x + 4;</code></td>
+ </tr>
+ <tr>
+ <td><code>-=</code></td>
+ <td>Subtraction assignment</td>
+ <td>Subtracts the value on the right from the variable value on the left, and returns the new variable value</td>
+ <td><code>x = 6;<br>
+ x -= 3;</code></td>
+ <td><code>x = 6;<br>
+ x = x - 3;</code></td>
+ </tr>
+ <tr>
+ <td><code>*=</code></td>
+ <td>Multiplication assignment</td>
+ <td>Multiples the variable value on the left by the value on the right, and returns the new variable value</td>
+ <td><code>x = 2;<br>
+ x *= 3;</code></td>
+ <td><code>x = 2;<br>
+ x = x * 3;</code></td>
+ </tr>
+ <tr>
+ <td><code>/=</code></td>
+ <td>Division assignment</td>
+ <td>Divides the variable value on the left by the value on the right, and returns the new variable value</td>
+ <td><code>x = 10;<br>
+ x /= 5;</code></td>
+ <td><code>x = 10;<br>
+ x = x / 5;</code></td>
+ </tr>
+ </tbody>
+</table>
+
+<p>Try typing some of the above examples into your console, to get an idea of how they work. In each case, see if you can guess what the value is before you type in the second line.</p>
+
+<p>Note that you can quite happily use other variables on the right hand side of each expression, for example:</p>
+
+<pre class="brush: js notranslate">var x = 3; // x contains the value 3
+var y = 4; // y contains the value 4
+x *= y; // x now contains the value 12</pre>
+
+<div class="note">
+<p><strong>Note</strong>: There are lots of <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment_operators">other assignment operators available</a>, but these are the basic ones you should learn now.</p>
+</div>
+
+<h2 id="Active_learning_sizing_a_canvas_box">Active learning: sizing a canvas box</h2>
+
+<p>In this exercise, you will manipulate some numbers and operators to change the size of a box. The box is drawn using a browser API called the {{domxref("Canvas API", "", "", "true")}}. There is no need to worry about how this works — just concentrate on the math for now. The width and height of the box (in pixels) are defined by the variables <code>x</code> and <code>y</code>, which are initially both given a value of 50.</p>
+
+<p>{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/maths/editable_canvas.html", '100%', 620)}}</p>
+
+<p><strong><a href="https://mdn.github.io/learning-area/javascript/introduction-to-js-1/maths/editable_canvas.html">Open in new window</a></strong></p>
+
+<p>In the editable code box above, there are two lines marked with a comment that we'd like you to update to make the box grow/shrink to certain sizes, using certain operators and/or values in each case. Let's try the following:</p>
+
+<ul>
+ <li>Change the line that calculates x so the box is still 50px wide, but the 50 is calculated using the numbers 43 and 7 and an arithmetic operator.</li>
+ <li>Change the line that calculates y so the box is 75px high, but the 75 is calculated using the numbers 25 and 3 and an arithmetic operator.</li>
+ <li>Change the line that calculates x so the box is 250px wide, but the 250 is calculated using two numbers and the remainder (modulo) operator.</li>
+ <li>Change the line that calculates y so the box is 150px high, but the 150 is calculated using three numbers and the subtraction and division operators.</li>
+ <li>Change the line that calculates x so the box is 200px wide, but the 200 is calculated using the number 4 and an assignment operator.</li>
+ <li>Change the line that calculates y so the box is 200px high, but the 200 is calculated using the numbers 50 and 3, the multiplication operator, and the addition assignment operator.</li>
+</ul>
+
+<p>Don't worry if you totally mess the code up. You can always press the Reset button to get things working again. After you've answered all the above questions correctly, feel free to play with the code some more or create your own challenges.</p>
+
+<h2 id="比較運算符">比較運算符</h2>
+
+<p>Sometimes we will want to run true/false tests, then act accordingly depending on the result of that test — to do this we use <strong>comparison operators</strong>.</p>
+
+<table class="standard-table">
+ <thead>
+ <tr>
+ <th scope="col">Operator</th>
+ <th scope="col">Name</th>
+ <th scope="col">Purpose</th>
+ <th scope="col">Example</th>
+ </tr>
+ <tr>
+ <td><code>===</code></td>
+ <td>Strict equality</td>
+ <td>Tests whether the left and right values are identical to one another</td>
+ <td><code>5 === 2 + 4</code></td>
+ </tr>
+ <tr>
+ <td><code>!==</code></td>
+ <td>Strict-non-equality</td>
+ <td>Tests whether the left and right values <strong>not</strong> identical to one another</td>
+ <td><code>5 !== 2 + 3</code></td>
+ </tr>
+ <tr>
+ <td><code>&lt;</code></td>
+ <td>Less than</td>
+ <td>Tests whether the left value is smaller than the right one.</td>
+ <td><code>10 &lt; 6</code></td>
+ </tr>
+ <tr>
+ <td><code>&gt;</code></td>
+ <td>Greater than</td>
+ <td>Tests whether the left value is greater than the right one.</td>
+ <td><code>10 &gt; 20</code></td>
+ </tr>
+ <tr>
+ <td><code>&lt;=</code></td>
+ <td>Less than or equal to</td>
+ <td>Tests whether the left value is smaller than or equal to the right one.</td>
+ <td><code>3 &lt;= 2</code></td>
+ </tr>
+ <tr>
+ <td><code>&gt;=</code></td>
+ <td>Greater than or equal to</td>
+ <td>Tests whether the left value is greater than or equal to the right one.</td>
+ <td><code>5 &gt;= 4</code></td>
+ </tr>
+ </thead>
+</table>
+
+<div class="note">
+<p><strong>Note</strong>: You may see some people using <code>==</code> and <code>!=</code> in their tests for equality and non-equality. These are valid operators in JavaScript, but they differ from <code>===</code>/<code>!==</code>. The former versions test whether the values are the same but not whether the values' datatypes are the same. The latter, strict versions test the equality of both the values and their datatypes. The strict versions tend to result in fewer errors, so we recommend you use them.</p>
+</div>
+
+<p>If you try entering some of these values in a console, you'll see that they all return <code>true</code>/<code>false</code> values — those booleans we mentioned in the last article. These are very useful, as they allow us to make decisions in our code, and they are used every time we want to make a choice of some kind. For example, booleans can be used to:</p>
+
+<ul>
+ <li>Display the correct text label on a button depending on whether a feature is turned on or off</li>
+ <li>Display a game over message if a game is over or a victory message if the game has been won</li>
+ <li>Display the correct seasonal greeting depending what holiday season it is</li>
+ <li>Zoom a map in or out depending on what zoom level is selected</li>
+</ul>
+
+<p>We'll look at how to code such logic when we look at conditional statements in a future article. For now, let's look at a quick example:</p>
+
+<pre class="brush: html notranslate">&lt;button&gt;Start machine&lt;/button&gt;
+&lt;p&gt;The machine is stopped.&lt;/p&gt;
+</pre>
+
+<pre class="brush: js notranslate">var btn = document.querySelector('button');
+var txt = document.querySelector('p');
+
+btn.addEventListener('click', updateBtn);
+
+function updateBtn() {
+ if (btn.textContent === 'Start machine') {
+ btn.textContent = 'Stop machine';
+ txt.textContent = 'The machine has started!';
+ } else {
+ btn.textContent = 'Start machine';
+ txt.textContent = 'The machine is stopped.';
+ }
+}</pre>
+
+<p>{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/maths/conditional.html", '100%', 100)}}</p>
+
+<p><strong><a href="https://mdn.github.io/learning-area/javascript/introduction-to-js-1/maths/conditional.html">Open in new window</a></strong></p>
+
+<p>You can see the equality operator being used just inside the <code>updateBtn()</code> function. In this case, we are not testing if two mathemetical expressions have the same value — we are testing whether the text content of a button contains a certain string — but it is still the same principle at work. If the button is currently saying "Start machine" when it is pressed, we change its label to  "Stop machine", and update the label as appropriate. If the button is currently saying "Stop machine" when it is pressed, we swap the display back again.</p>
+
+<div class="note">
+<p><strong>Note</strong>: Such a control that swaps between two states is generally referred to as a <strong>toggle</strong>. It toggles between one state and another — light on, light off, etc.</p>
+</div>
+
+<h2 id="Summary">Summary</h2>
+
+<p>In this article we have covered the fundamental information you need to know about numbers in JavaScript, for now. You'll see numbers used again and again, all the way through your JavaScript learning, so it's a good idea to get this out of the way now. If you are one of those people that doesn't enjoy math, you can take comfort in the fact that this chapter was pretty short.</p>
+
+<p>In the next article, we'll explore text and how JavaScript allows us to manipulate it.</p>
+
+<div class="note">
+<p><strong>Note</strong>: If you do enjoy math and want to read more about how it is implemented in JavaScript, you can find a lot more detail in MDN's main JavaScript section. Great places to start are our <a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates">Numbers and dates</a> and <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">Expressions and operators</a> articles.</p>
+</div>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps")}}</p>
+
+<h2 id="在這個學習模組中">在這個學習模組中</h2>
+
+<ul>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_is_JavaScript">什麼是 JavaScript?</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/A_first_splash">和 JavaScript 的第一次接觸</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_went_wrong">什麼出錯了? JavaScript 的疑難排解(除錯)</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Variables">儲存你需要的資訊 — 變數</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Math">JavaScript 的基本運算— 數字 與 運算子</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Strings">處理文字 — JavaScript 的字串</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Useful_string_methods">有用的字串方法</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Arrays">陣列</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Silly_story_generator">附錄:笑話產生器</a></li>
+</ul>
diff --git a/files/zh-tw/learn/javascript/first_steps/silly_story_generator/index.html b/files/zh-tw/learn/javascript/first_steps/silly_story_generator/index.html
new file mode 100644
index 0000000000..2659623210
--- /dev/null
+++ b/files/zh-tw/learn/javascript/first_steps/silly_story_generator/index.html
@@ -0,0 +1,149 @@
+---
+title: 傻故事產生器
+slug: Learn/JavaScript/First_steps/Silly_story_generator
+tags:
+ - JavaScript
+ - 初學者
+ - 字串
+ - 測試
+ - 變數
+ - 運算子
+ - 陣列
+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">在本次評估中,您被賦予的任務內容將與本單元學習到的知識息息相關,並將其應用於創建一個能隨機生成傻故事的有趣應用程式。 祝玩的開心!</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">事先具備:</th>
+ <td>進行此測驗之前你應先完成此區塊的所有內容</td>
+ </tr>
+ <tr>
+ <th scope="row">目標:</th>
+ <td>測試對於JavaScript基礎的理解程度, 例如 變數, 數字, 運算子, 字串 以及陣列.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="前置作業">前置作業</h2>
+
+<p>在開始本測驗前,你應該:</p>
+
+<ul>
+ <li>開啟右方網頁: <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/assessment-start/index.html">grab the HTML file</a> ,將HTML範本儲存到您的本地電腦的新資料夾中,並命名為<code>index.html</code> 。範本也包含相應的CSS檔案。</li>
+ <li>開啟右方網頁: <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/assessment-start/raw-text.txt">page containing the raw text</a> ,並保持網頁開啟在瀏覽器的另一分頁上,以便稍後使用。</li>
+</ul>
+
+<div class="note">
+<p><strong>備註</strong>: 除了將檔案下載到自己的電腦中,您也能使用線上編輯程式的網頁,像是: <a class="external external-icon" href="http://jsbin.com/">JSBin</a> 或者<a class="external external-icon" href="https://thimble.mozilla.org/">Thimble</a> 來完成評估測驗。您可以將 HTML, CSS 以及 JavaScript 貼到前述的線上編輯器中。如果您使用的線上編輯器沒有獨立給 JavaScript 的編輯區,您也能透過<code>&lt;script&gt;</code>直接將JS語法放到 HTML檔案中。</p>
+</div>
+
+<h2 id="任務簡介">任務簡介</h2>
+
+<p>透過前述網頁您已經得到初版HTML/CSS 與一些JavaScript 字串、函數;您需要再寫一些必要的JavaScript語法來將這些檔案轉變為可運作的程式,任務如下: </p>
+
+<ul>
+ <li>當 "Generate random story" (產生隨機故事)的按鈕被點擊,請產出一則傻故事</li>
+ <li>若在點擊產生故事按鈕前將自定義名字輸入於輸入框"Enter custom name" (譯:輸入自定義名字),則將故事中預設的名字 "Bob" 代換為自定義名字</li>
+ <li>若在點擊產生故事按鈕前,也點擊UK的單選按鈕,則將預設的美制重量、溫度單位轉換為英制單位</li>
+ <li>每點擊一次產生故事的按鈕,即產生新一則隨機傻故事(不限次數)</li>
+</ul>
+
+<p>以下截圖為完成品的範例:</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13667/assessment-1.png" style="border-style: solid; border-width: 1px; display: block; margin: 0px auto;"></p>
+
+<p>點擊右方連結可以參考與測試完成品: <a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/assessment-finished/">have a look at the finished example</a> (請不要偷看原始碼喔!)</p>
+
+<h2 id="任務開始">任務開始</h2>
+
+<p>以下清楚地描述了完成任務需要哪些動作。</p>
+
+<p>基本設定:</p>
+
+<ol>
+ <li>在有<code>index.html</code>的資料夾中建立一個新檔案稱之為 <code>main.js</code></li>
+ <li>請在<code>index.html</code>中引用第一點建立的外部JavaScript 檔案,引用方法是在<code>&lt;/body&gt;</code> tag 前插入一組 {{htmlelement("script")}}元素 ,並在opening tag上加入<code>src=" main.js"​​​​​​</code></li>
+</ol>
+
+<p>初始化變數與函數:</p>
+
+<ol>
+ <li>在原始文件檔中(raw text file),請複製標題1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS" 以下到第2點前的所有程式碼,並貼到<code>main.js</code>中。這給你三個變數來標記:文字輸入框 "Enter custom name" (輸入自定義名字) ,變數為 (<code>customName</code>) 與按鈕 "Generate random story"(產生隨機故事) ,變數為 (<code>randomize</code>), 以及HTML中接近body底部的 {{htmlelement("p")}} 元素,故事將會被複製進第三個變數(<code>story</code>)中。此外您還會得到一個函數稱為: <code>randomValueFromArray()</code> ,從命名中可以得知這是一個陣列,它會隨機提供一則儲存其中的故事。</li>
+ <li>接著讓我們查看原始文件檔中(raw text file)的第2點: "2. RAW TEXT STRINGS"。 其包含的這些字串在程式運行時會被放進來,請幫忙在<code>main.js</code>中將這些字串分別存進對應的變數裡:
+ <ol>
+ <li>將第一行超級長的字串存進變數 <code>storyText</code>中。</li>
+ <li>將第一組三個字串存進一陣列,並命名為<code>insertX</code>。</li>
+ <li>將第二組三個字串存進一陣列,並命名為<code>insertY</code>.</li>
+ <li>將第三組三個字串存進一陣列,並命名為<code>insertZ</code>.</li>
+ </ol>
+ </li>
+</ol>
+
+<p>放置事件監聽器與未完善的函數:</p>
+
+<ol>
+ <li>再度回到原始文件檔中(raw text file)</li>
+ <li>複製第3標題,"3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION" 以下的內容,並貼到 <code>main.js</code> 檔案中的最下方,這包含:
+ <ul>
+ <li>給變數<code>randomize</code>增加一個點擊事件監聽器(clickevent listener) ,所以當產生故事的按鈕被點擊,<code>result()</code>函數會運行 。</li>
+ <li>增加一個部分完成的函數 <code>result()</code> ,完成測驗您需要完善這個函數。</li>
+ </ul>
+ </li>
+</ol>
+
+<p>完善 <code>result()</code> 函數:</p>
+
+<ol>
+ <li>創造一個新變數稱為:<code>newStory</code>,讓這個變數的值等於<code>storyText</code>;我們需要這個變數以便每次產生故事按鈕被點擊時,函數都能再次運作並產生新故事,如果我們只在<code>storyText</code>之上做改變,我們只能產生一次新故事。</li>
+ <li>額外增加三個變數:<code>xItem</code>、<code>yItem</code> 與 <code>zItem</code>,並使這三個變數等於函數<code>randomValueFromArray()</code>中三個陣列的結果(每次會從各陣列中隨機挑出一項)。舉例,你能透過寫<code>randomValueFromArray(insertX)</code>來從<code>insertX</code>得到任一隨機字串。</li>
+ <li>接著我們需要將<code>newStory</code>中三個placeholders字串 <code>:insertx:</code>、<code>:inserty:</code>跟 <code>:insertz:</code>換成<code>xItem</code>、<code>yItem</code>、 <code>zItem</code>。有些字串方法在這裡特別有用,請讓字串方法的返回值等於 <code>newStory</code> ,所以之後每次 <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 farenheit' 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 notranslate">document.querySelector('html').style.backgroundColor = 'red';</pre>
+ </li>
+ <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round">Math.round()</a> 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>var 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="測驗一下">測驗一下</h2>
+
+<p>如果您將這個測驗視為正規課程的一部分,建議將成果提供您的老師或指導者以利幫助您達到最好的學習效益。如果您是自學者,您可以輕鬆的透過右方網頁 <a href="https://discourse.mozilla.org/t/silly-story-generator-assessment/24686">discussion thread for this exercise</a> 得到建議,或者在<a href="https://wiki.mozilla.org/IRC">Mozilla IRC</a>上的 <a href="irc://irc.mozilla.org/mdn">#mdn</a> IRC 頻道。提醒您:第一次嘗試這個測驗時,作弊可不會得到任何收穫喔!</p>
+
+<p>{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}</p>
+
+
+
+<h2 id="相關學習模組">相關學習模組</h2>
+
+<ul>
+ <li><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/First_steps/What_is_JavaScript">什麼是 JavaScript?</a></li>
+ <li><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/First_steps/A_first_splash">和 JavaScript 的第一次接觸</a></li>
+ <li><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/First_steps/What_went_wrong">什麼出錯了? JavaScript 的疑難排解(除錯)</a></li>
+ <li><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/First_steps/Variables">儲存你需要的資訊 — 變數</a></li>
+ <li><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/First_steps/Math">JavaScript 的基本運算— 數字 與 運算子</a></li>
+ <li><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/First_steps/Strings">處理文字 — JavaScript 的字串</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a> <a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/First_steps/Useful_string_methods">有用的字串方法</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a> <a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/First_steps/Arrays">陣列</a></li>
+ <li><a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/First_steps/Silly_story_generator">傻故事產生器</a></li>
+</ul>
diff --git a/files/zh-tw/learn/javascript/first_steps/strings/index.html b/files/zh-tw/learn/javascript/first_steps/strings/index.html
new file mode 100644
index 0000000000..8e4a3b1f6a
--- /dev/null
+++ b/files/zh-tw/learn/javascript/first_steps/strings/index.html
@@ -0,0 +1,352 @@
+---
+title: 處理文字 - JavaScript中的字串
+slug: Learn/JavaScript/First_steps/Strings
+tags:
+ - JavaScript
+ - 初學者
+ - 字串
+ - 引號
+ - 文章
+ - 連接字串
+translation_of: Learn/JavaScript/First_steps/Strings
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps")}}</div>
+
+<p class="summary">接下來我們將把注意力轉向字串——這就是程式設計中調用的文字片段。在本文中,我們將介紹在學習JavaScript時您應該了解所有有關字串的常見事項,例如建立字串,跳脫字串中的引號以及將字串連接在一起。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">先備知識:</th>
+ <td>基本的電腦素養、對 HTML 與 CSS 有基本的認識、對 JavaScript 有認識。</td>
+ </tr>
+ <tr>
+ <th scope="row">目標:</th>
+ <td>熟悉 JavaScript 字串的基礎。</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="文字的力量">文字的力量</h2>
+
+<p>文字對人類而言非常重要——它關乎我們如何交流、溝通。Web 以文字為基底的媒介,它的設計讓人類可以進行交流並分享資訊,因此掌握文字如何在 Web 上呈現是很有用的。{{glossary("HTML")}} 提供文字的結構以及定義;{{glossary("CSS")}} 讓我們更精確地設定樣式;而 JavaScript 則包含許多操作字串的特性,例如:製作客製化的歡迎訊息、正確地顯示所需的文字標籤、排列所需的詞語順序等。</p>
+
+<p>到目前為止,所有我們課程上的編碼幾乎都包含一些字串的操作。</p>
+
+<h2 id="字串_—_基礎">字串 — 基礎</h2>
+
+<p>剛開始你會覺得字串與數字的處理方式很類似,但當你越深入就會了解到一些明顯的差異。讓我們從在 console 裡輸入一些基本的程式行來熟悉它吧!在下方,我們提供一個 Console (你也可以另開一個頁籤或視窗<a href="https://mdn.github.io/learning-area/javascript/introduction-to-js-1/variables/index.html">使用他</a> ,或者使用瀏覽器的<a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">開發者工具</a>)。</p>
+
+<div class="hidden">
+<h6 id="Hidden_code">Hidden code</h6>
+
+<pre class="brush: html notranslate">&lt;!DOCTYPE html&gt;
+&lt;html&gt;
+ &lt;head&gt;
+ &lt;meta charset="utf-8"&gt;
+ &lt;title&gt;JavaScript console&lt;/title&gt;
+ &lt;style&gt;
+ * {
+ 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;
+ }
+
+ &lt;/style&gt;
+ &lt;/head&gt;
+ &lt;body&gt;
+
+
+ &lt;/body&gt;
+
+ &lt;script&gt;
+ 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 = '&gt;';
+ inputDiv.appendChild(inputPara);
+ inputDiv.appendChild(inputForm);
+ document.body.appendChild(inputDiv);
+
+ if(document.querySelectorAll('div').length &gt; 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();
+
+ &lt;/script&gt;
+&lt;/html&gt;</pre>
+</div>
+
+<p>{{ EmbedLiveSample('Hidden_code', '100%', 300, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<h3 id="建立字串">建立字串</h3>
+
+<ol>
+ <li>首先,先輸入下面幾行程式碼:
+ <pre class="brush: js notranslate">let string = 'The revolution will not be televised.';
+string;</pre>
+ 就像我們對數字的操作,我們聲明一個變數,並用一個值(字串)來初始化它,而後傳回這個值。唯一的差異在於,你需要用引號包住你的值。</li>
+ <li>如果你沒有使用引號包住值,或缺少單一邊的引號,都會導致錯誤產生。試著輸入下面幾行程式碼:
+ <pre class="brush: js example-bad notranslate">let badString = This is a test;
+let badString = 'This is a test;
+let badString = This is a test';</pre>
+ 上述的程式無法運作,因為未使用引號包圍的文字都將被視為變數名稱、屬性名稱和保留字等。如果瀏覽器無法辨識它,便會產生錯誤(例如:「missing ; before statement」)。如果瀏覽器可以識別字段從哪裡開始,但無法找到字段的終點,意即缺少第二個引號,則會產生「unterminated string literal」的錯誤。如果你的程式出現了這樣的錯誤,檢查並確認自己的字串是否遺漏了任何引號。</li>
+ <li>如果你先定義了變數 <code>string</code> ,則以下程式碼可以正常運作。馬上來試試看:
+ <pre class="brush: js notranslate">let badString = string;
+badString;</pre>
+ <code>badString</code> 會被設定跟 <code>string</code> 具有一樣的值。</li>
+</ol>
+
+<h3 id="單引號與雙引號">單引號與雙引號</h3>
+
+<ol>
+ <li>在 JavaScript 中,你可以選擇用單引號或雙引號來包住字串。兩種方式都可行:
+ <pre class="brush: js notranslate">let sgl = 'Single quotes.';
+let dbl = "Double quotes";
+sgl;
+dbl;</pre>
+ </li>
+ <li>兩種之間的差異非常小,取決於你個人的習慣與喜好。你可以選擇一種,並且固定使用它。交互使用兩種方式,容易造成混亂。特別是當你使用兩種不同的引號包住一個字串!這會導致錯誤回傳:
+ <pre class="brush: js example-bad notranslate">let badQuotes = 'What on earth?";</pre>
+ </li>
+ <li>瀏覽器會認為字串並沒有結束,沒有作為包住字串的引號,是可以出現在字串裡面的。看看下面的例子,兩種都是可行的:
+ <pre class="brush: js notranslate">let sglDbl = 'Would you eat a "fish supper"?';
+let dblSgl = "I'm feeling blue.";
+sglDbl;
+dblSgl;</pre>
+ </li>
+ <li>但是,字串中不可以再使用那個作為包住字串的引號。以下的程式行會出錯,因為瀏覽器無法判斷字串的結尾:
+ <pre class="brush: js example-bad notranslate">let bigmouth = 'I've got no right to take my place...';</pre>
+ This leads us very nicely into our next subject.</li>
+</ol>
+
+<h3 id="字串中的跳脫字元(Escaping_characters)">字串中的跳脫字元(Escaping characters)</h3>
+
+<p>要修復先前出錯的那一行程式碼,我們需要解決引號的問題。跳脫字元(Escaping characters)的意思是我們需要確保它們被辨識為文字,而非程式碼本身。在 JavaScript 中,我們在字元的前面放一個反斜線解決這個問題。試試看這個:</p>
+
+<pre class="brush: js notranslate">let bigmouth = 'I\'ve got no right to take my place...';
+bigmouth;</pre>
+
+<p>這是可行的!你可以用一樣的方法跳脫其他字元,例如 <code>\"</code>。除此之外,還有一些特殊方法。更詳細的部分,請參閱<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Escape_notation">跳脫符號</a> 。</p>
+
+<h2 id="連接字串(Concatenating_strings)">連接字串(Concatenating strings)</h2>
+
+<ol>
+ <li>連接(Concatenate)是一個新潮的程式用語。在 JavaScript 中,使用加號(+)將字串連接;這也是我們做數字相加的方式。但在這個狀況下,它有不同的作用。讓我們在 console 中示範:</li>
+ <li>
+ <pre class="brush: js notranslate">let one = 'Hello, ';
+let two = 'how are you?';
+let joined = one + two;
+joined;</pre>
+ 這邊的結果是 <code>joined</code>  這個變數中,有了 「Hello, how are you?」這個值。</li>
+ <li>在上一個範例中,我們只連接了兩個字串。但只要你在兩個字串之間加上 <code>+</code> ,那你要連接幾個都可以。試試看這個:
+ <pre class="brush: js notranslate">let multiple = one + one + one + one + two;
+multiple;</pre>
+ </li>
+ <li>你也可以結合變數和字串。試試看這個:
+ <pre class="brush: js notranslate">let response = one + 'I am fine — ' + two;
+response;</pre>
+ </li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: 當你輸入一個字串在你的程式碼中,並用單引號或雙引號將它括起來,它稱為<strong>字串文字</strong>(<strong>string literal</strong>)。</p>
+</div>
+
+<h3 id="Concatenation_in_context">Concatenation in context</h3>
+
+<p>讓我們看看實際運用連接字串的例子——以下是這堂課中稍早的範例:</p>
+
+<pre class="brush: html notranslate">&lt;button&gt;Press me&lt;/button&gt;</pre>
+
+<pre class="brush: js notranslate">const button = document.querySelector('button');
+
+button.onclick = function() {
+ let name = prompt('What is your name?');
+ alert('Hello ' + name + ', nice to see you!');
+}</pre>
+
+<p>{{ EmbedLiveSample('Concatenation_in_context', '100%', 50, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<p>在程式第四行我們用了 {{domxref("window.prompt()", "window.prompt()")}} 這個函式,可以要求使用者透過彈出的對話框去回答問題,並將使用者輸入的文字儲存在給訂的變數內(在這個例子中就是 <code>name</code>)。接著我們在第五行用了 {{domxref("window.alert()", "window.alert()")}} 函式,顯示另一個彈出視窗,以連接的方式將兩段字串文字以及 <code>name</code> 這個變數結合成一個字串。</p>
+
+<h3 id="數字_vs._字串">數字 vs. 字串</h3>
+
+<ol>
+ <li>那麼我們將字串和數字連接會發生什麼事呢?讓我們在console中試試看:
+ <pre class="brush: js notranslate">'Front ' + 242;
+</pre>
+ 或許你預期會跑出錯誤訊息,但看來依然正常運作。若將字串表示成數字似乎不太合理,但將數字表示成字串看來是可行的,所以瀏覽器便會巧妙地將數字轉換成字串,並將這兩個字串連接在一起。</li>
+ <li>你也可以用兩個數字做這個例子 — 將這兩個數字包在引號中強制將它們轉換成字串。試試看(並使用typeof這個運算子去檢查變數是數字或字串):
+ <pre class="brush: js notranslate">let myDate = '19' + '67';
+typeof myDate;</pre>
+ </li>
+ <li>如果你想轉換數字變數成字串,但不要更動到原本的變數;或是想轉換字串變數成數字,也不要更動到原本的變數,你可以使用以下兩種方式:
+ <ul>
+ <li>物件 {{jsxref("Number")}} 會將欲處理的變數轉換成數字(如果可行的話)。試試以下例子:
+ <pre class="brush: js notranslate">let myString = '123';
+let myNum = Number(myString);
+typeof myNum;</pre>
+ </li>
+ <li>另一方面,也有 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString">toString()</a></code> 方法能夠讓數字轉換為相等的字串。試試看:
+ <pre class="brush: js notranslate">let myNum = 123;
+let myString = myNum.toString();
+typeof myString;</pre>
+ </li>
+ </ul>
+ 這些結構在某些情況相當好用。舉例來說:如果使用者在文字表單中輸入了一個數字,這個數字將會是字串格式。而若想要把這個數字加上另一個數字,那你會希望它是數字格式(才能做數字相加),所以可以使用 <code>Number()</code> 來處理這個情況。可以看看實際案例:<a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/first-splash/number-guessing-game.html#L61">猜數字遊戲, 第61行</a>。</li>
+</ol>
+
+<h2 id="模版字符串Template_literals">模版字符串(Template literals)</h2>
+
+<p>另一種你會遇上的字串語法是<strong>模版字符串(template literals)</strong> (也稱做模版字串 template strings)。這是一種更新的語法提供更彈性、簡單的方式去理解字串。</p>
+
+<div class="blockIndicator note">
+<p><strong>Note</strong>: 嘗試在你的瀏覽器上測試下面的範例,來看看會得到什麼結果。</p>
+</div>
+
+<p>將標準字串轉變為模版字符串,你需要將引號 (<code>' '</code>, or <code>" "</code>) 換為重音符 (backtick characters (<code>` `</code>) ),接著來看一個簡單的例子:</p>
+
+<pre class="brush: js notranslate">let song = 'Fight the Youth';</pre>
+
+<p>轉換成模版字符串會像這樣子:</p>
+
+<pre class="brush: js notranslate">song = `Fight the Youth`;</pre>
+
+<p>如果我們想要連接字串,或是將算式的結果包含在裡面,用傳統的字串去寫會很瑣碎且麻煩:</p>
+
+<pre class="brush: js notranslate">let score = 9;
+let highestScore = 10;
+let output = 'I like the song "' + song + '". I gave it a score of ' + (score/highestScore * 100) + '%.';</pre>
+
+<p>模版字符串能大量簡化這串程式碼:</p>
+
+<pre class="brush: js notranslate">output = `I like the song "${ song }". I gave it a score of ${ score/highestScore * 100 }%.`;</pre>
+
+<p>全部一串都只需要包含在一對重音符號裡,不再需要切開、合起一堆字串碎片。<br>
+ 當你想要包含變數或者算式在字串裡時,你只需要將它放在 <em>佔位符 </em><code>${ } </code>裡。</p>
+
+<p>你能將複雜的算式包含在模版字符串裡,舉個例子:</p>
+
+<pre class="brush: js notranslate">let examScore = 45;
+let examHighestScore = 70;
+examReport = `You scored ${ examScore }/${ examHighestScore } (${ Math.round((examScore/examHighestScore*100)) }%). ${ examScore &gt;= 49 ? 'Well done, you passed!' : 'Bad luck, you didn\'t pass this time.' }`;
+</pre>
+
+<ul>
+ <li>前兩個佔位符非常好理解,字串裡只包含了單一值。</li>
+ <li>第三個計算了一個百分比的結果且四捨五入進整數。</li>
+ <li>第四個使用了三元運算符來檢查分數是否高於指定分數且印出一個通過或著失敗的訊息結果。</li>
+</ul>
+
+<p>另一個可以注意的點是,如果你想要將傳統字串拆分成多行,你需要加上一個斷行字母, <code>\n</code></p>
+
+<pre class="brush: js notranslate">output = 'I like the song "' + song + '".\nI gave it a score of ' + (score/highestScore * 100) + '%.';</pre>
+
+<p>模版字符串保留了程式碼中的斷行方式,所以不再需要使用斷行字母。<br>
+ 這樣也能達到相同的結果:</p>
+
+<pre class="brush: js notranslate">output = `I like the song "${ song }".
+I gave it a score of ${ score/highestScore * 100 }%.`;</pre>
+
+<p>我們建議你盡可能習慣使用模版字符串。現今流行的瀏覽器都能完好的支援它,只有一個地方你能發現它並不支援外: Internet Explorer。<br>
+ 我們有許多的例子仍然使用目前標準的字串語法,但我們未來將會加入更多模版字符串的應用。</p>
+
+<p>來我們的<a href="/en-US/docs/Web/JavaScript/Reference/Template_literals">Template literals</a> 相關頁面看看更多的範例與進階的特色細節。</p>
+
+<h2 id="測試您的技能!">測試您的技能!</h2>
+
+<p>你已到達文章的結尾了,但你能記得最重要的資訊嗎?<br>
+ 在繼續學習之前,你可以找些難一點的測驗,來檢測你有記得這些知識 —  <a href="/en-US/docs/Learn/JavaScript/First_steps/Test_your_skills:_Strings">Test your skills: Strings</a>. 記住,接下來的文章也需要這些知識,所以你可能想先看看。</p>
+
+<h2 id="結語">結語</h2>
+
+<p>以上是JavaScript中基礎的字串觀念。下個文章中,我們會依循這些概念並試試一些適用於字串的內建方法,進而運用這些方法讓字串能照我們想要的方式呈現。</p>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps")}}</p>
+
+<h2 id="在這個學習模組中">在這個學習模組中</h2>
+
+<ul>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_is_JavaScript">什麼是 JavaScript?</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/A_first_splash">和 JavaScript 的第一次接觸</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_went_wrong">什麼出錯了?JavaScript 的疑難排解(除錯)</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Variables">儲存你需要的資訊 — 變數</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Math">JavaScript 的基本運算— 數字 與 運算子</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Strings">處理文字 - JavaScript 的字串</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Useful_string_methods">有用的字串方法</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Arrays">陣列</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Silly_story_generator">附錄:笑話產生器</a></li>
+</ul>
diff --git a/files/zh-tw/learn/javascript/first_steps/useful_string_methods/index.html b/files/zh-tw/learn/javascript/first_steps/useful_string_methods/index.html
new file mode 100644
index 0000000000..e5efb51e1b
--- /dev/null
+++ b/files/zh-tw/learn/javascript/first_steps/useful_string_methods/index.html
@@ -0,0 +1,714 @@
+---
+title: 有用的字符串方法
+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">現在我們已經了解了字符串的基礎知識,讓我們開始思考我們可以使用內置方法對字符串執行哪些有用的操作,例如查找文本字符串的長度,連接和拆分字符串 ,將字符串中的一個字符替換為另一個字符,等等。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">先備知識:</th>
+ <td>基礎的電腦素養、基本的HTML和CSS、以及清楚什麼是JavaScript。</td>
+ </tr>
+ <tr>
+ <th scope="row">目標:</th>
+ <td>了解字串是物件,學習使用一些能夠應用這些字串的基礎方法。</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="把字串當作物件">把字串當作物件</h2>
+
+<p id="Useful_string_methods">我們曾經說過,現在我們重申一遍—在javascript中,一切東西都可以被當作物件。例如我們創建一個字串。</p>
+
+<pre class="brush: js notranslate">var string = 'This is my string';</pre>
+
+<p>你的變數成為一個字串的實體物件,因此它將有許多性質(properties)與功能(methods)可以使用。</p>
+
+<p>你的變數成為一個字串的實體物件,因此它將有許多性質(properties)與功能(methods)可以使用。你可以到 {{jsxref("String")}} 物件頁面的左方列表查看這些性質與功能!</p>
+
+<p><strong>好的,在你腦袋燒壞之前先別擔心!</strong>在這趟學習旅程中,關於這些大部分對於現在的你其實還不需要知道。不過有一些你可能會經常使用,我們將在這裡介紹。</p>
+
+<p>Let's enter some examples into a fresh console. We've provided one below (you can also <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, or use the <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">browser developer console</a> if you'd prefer).</p>
+
+<div class="hidden">
+<h6 id="Hidden_code">Hidden code</h6>
+
+<pre class="brush: html notranslate">&lt;!DOCTYPE html&gt;
+&lt;html&gt;
+ &lt;head&gt;
+ &lt;meta charset="utf-8"&gt;
+ &lt;title&gt;JavaScript console&lt;/title&gt;
+ &lt;style&gt;
+ * {
+ 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;
+ }
+
+ &lt;/style&gt;
+ &lt;/head&gt;
+ &lt;body&gt;
+
+
+ &lt;/body&gt;
+
+ &lt;script&gt;
+ 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 = '&gt;';
+ inputDiv.appendChild(inputPara);
+ inputDiv.appendChild(inputForm);
+ document.body.appendChild(inputDiv);
+
+ 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();
+
+ &lt;/script&gt;
+&lt;/html&gt;</pre>
+</div>
+
+<p>{{ EmbedLiveSample('Hidden_code', '100%', 300, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<h3 id="找出字串的長度(length)">找出字串的長度(length)</h3>
+
+<p>這很簡單,你可以用 {{jsxref("String.prototype.length", "length")}} 屬性。試著輸入下面幾行:</p>
+
+<pre class="brush: js notranslate">var browserType = 'mozilla';
+browserType.length;</pre>
+
+<p>結果應該會回傳數字7,因為 "mozilla" 字元長度是7。 這在很多狀況下很好用,舉例來說:你會想知道序列的長度,這樣才能將這些序列按照長度排序,或是讓使用者知道他們輸入的名稱是否太長。</p>
+
+<h3 id="取得字串中的特定字元(string_character)">取得字串中的特定字元(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 notranslate">browserType[0];</pre>
+
+<p>記得電腦計數從0開始,不是1! 如果要在<em>任何</em>一個字串中取得最後一個字元,我們可以使用以下程式碼,結合了取得字元的技巧和上面學過的長度屬性:</p>
+
+<pre class="brush: js notranslate">browserType[browserType.length-1];</pre>
+
+<p>"mozilla" 這個詞的長度是7,但因為電腦是從0開始計數,所以最後一個位置是6,因此我們會將 <code>length-1</code> 。你也可以試試用這個方法找各序列的第一個字母,並將這些序列按字母順序排好 。</p>
+
+<h3 id="尋找字串中的子字串(substring)並提出子字串">尋找字串中的子字串(substring)並提出子字串</h3>
+
+<ol>
+ <li>Sometim有時候你會想搜尋是否有一個較小的字串存在於比較大的字串中(<em>我們通常會說是否有個子字串存在於字串中</em>)。這可以用 {{jsxref("String.prototype.indexOf()", "indexOf()")}} 方法,當中需要一個參數( {{glossary("parameter")}} ),也就是你想搜尋的子字串:</li>
+ <li>
+ <pre class="brush: js notranslate">browserType.indexOf('zilla');</pre>
+ 結果會傳回2,因為子字串 "zilla" 在 "mozilla" 中是從位置2開始的。(依然要記得電腦計數是從0開始)。這個方法可以用篩選字串,舉例來說:我們有一串網址的清單,而我們只想印出那些包含 "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 notranslate">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 notranslate">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 notranslate">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 notranslate">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="改變大小寫">改變大小寫</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 notranslate">var radData = 'My NaMe Is MuD';
+radData.toLowerCase();
+radData.toUpperCase();</pre>
+
+<h3 id="更動部分字串">更動部分字串</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 notranslate">browserType.replace('moz','van');</pre>
+
+<p>Note that to actually get the updated value reflected in 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 notranslate">&lt;h2&gt;Live output&lt;/h2&gt;
+
+&lt;div class="output" style="min-height: 125px;"&gt;
+
+&lt;ul&gt;
+
+&lt;/ul&gt;
+
+&lt;/div&gt;
+
+&lt;h2&gt;Editable code&lt;/h2&gt;
+&lt;p class="a11y-label"&gt;Press Esc to move focus away from the code area (Tab inserts a tab character).&lt;/p&gt;
+
+&lt;textarea id="code" class="playable-code" style="height: 290px; width: 95%"&gt;
+var list = document.querySelector('.output ul');
+list.innerHTML = '';
+var 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 (var i = 0; i &lt; greetings.length; i++) {
+ var input = greetings[i];
+ // Your conditional test needs to go inside the parentheses
+ // in the line below, replacing what's currently there
+ if (greetings[i]) {
+ var result = input;
+ var listItem = document.createElement('li');
+ listItem.textContent = result;
+ list.appendChild(listItem);
+ }
+}
+&lt;/textarea&gt;
+
+&lt;div class="playable-buttons"&gt;
+ &lt;input id="reset" type="button" value="Reset"&gt;
+ &lt;input id="solution" type="button" value="Show solution"&gt;
+&lt;/div&gt;
+</pre>
+
+<pre class="brush: css notranslate">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 notranslate">var textarea = document.getElementById('code');
+var reset = document.getElementById('reset');
+var solution = document.getElementById('solution');
+var code = textarea.value;
+var 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();
+});
+
+var jsSolution = 'var list = document.querySelector(\'.output ul\');\nlist.innerHTML = \'\';\nvar 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(var i = 0; i &lt; greetings.length; i++) {\n var input = greetings[i];\n if(greetings[i].indexOf(\'Christmas\') !== -1) {\n var result = input;\n var listItem = document.createElement(\'li\');\n listItem.textContent = result;\n list.appendChild(listItem);\n }\n}';
+var 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) {
+ var scrollPos = textarea.scrollTop;
+ var caretPos = textarea.selectionStart;
+
+ var front = (textarea.value).substring(0, caretPos);
+ var 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 notranslate">&lt;h2&gt;Live output&lt;/h2&gt;
+
+&lt;div class="output" style="min-height: 125px;"&gt;
+
+&lt;ul&gt;
+
+&lt;/ul&gt;
+
+&lt;/div&gt;
+
+&lt;h2&gt;Editable code&lt;/h2&gt;
+&lt;p class="a11y-label"&gt;Press Esc to move focus away from the code area (Tab inserts a tab character).&lt;/p&gt;
+
+&lt;textarea id="code" class="playable-code" style="height: 250px; width: 95%"&gt;
+var list = document.querySelector('.output ul');
+list.innerHTML = '';
+var cities = ['lonDon', 'ManCHESTer', 'BiRmiNGHAM', 'liVERpoOL'];
+for(var i = 0; i &lt; cities.length; i++) {
+ var input = cities[i];
+ // write your code just below here
+
+ var result = input;
+ var listItem = document.createElement('li');
+ listItem.textContent = result;
+ list.appendChild(listItem);
+}
+&lt;/textarea&gt;
+
+&lt;div class="playable-buttons"&gt;
+ &lt;input id="reset" type="button" value="Reset"&gt;
+ &lt;input id="solution" type="button" value="Show solution"&gt;
+&lt;/div&gt;
+</pre>
+
+<pre class="brush: css notranslate">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 notranslate">var textarea = document.getElementById('code');
+var reset = document.getElementById('reset');
+var solution = document.getElementById('solution');
+var code = textarea.value;
+var 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();
+});
+
+var jsSolution = 'var list = document.querySelector(\'.output ul\');\nlist.innerHTML = \'\';\nvar cities = [\'lonDon\', \'ManCHESTer\', \'BiRmiNGHAM\', \'liVERpoOL\'];\n\nfor(var i = 0; i &lt; cities.length; i++) {\n var input = cities[i];\n var lower = input.toLowerCase();\n var firstLetter = lower.slice(0,1);\n var capitalized = lower.replace(firstLetter,firstLetter.toUpperCase());\n var result = capitalized;\n var listItem = document.createElement(\'li\');\n listItem.textContent = result;\n list.appendChild(listItem);\n\n}';
+var 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) {
+ var scrollPos = textarea.scrollTop;
+ var caretPos = textarea.selectionStart;
+
+ var front = (textarea.value).substring(0, caretPos);
+ var 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 class="notranslate">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 class="notranslate">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 notranslate">&lt;h2&gt;Live output&lt;/h2&gt;
+
+&lt;div class="output" style="min-height: 125px;"&gt;
+
+&lt;ul&gt;
+
+&lt;/ul&gt;
+
+&lt;/div&gt;
+
+&lt;h2&gt;Editable code&lt;/h2&gt;
+&lt;p class="a11y-label"&gt;Press Esc to move focus away from the code area (Tab inserts a tab character).&lt;/p&gt;
+
+&lt;textarea id="code" class="playable-code" style="height: 285px; width: 95%"&gt;
+var list = document.querySelector('.output ul');
+list.innerHTML = '';
+var stations = ['MAN675847583748sjt567654;Manchester Piccadilly',
+ 'GNF576746573fhdg4737dh4;Greenfield',
+ 'LIV5hg65hd737456236dch46dg4;Liverpool Lime Street',
+ 'SYB4f65hf75f736463;Stalybridge',
+ 'HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield'];
+
+for (var i = 0; i &lt; stations.length; i++) {
+ var input = stations[i];
+ // write your code just below here
+
+ var result = input;
+ var listItem = document.createElement('li');
+ listItem.textContent = result;
+ list.appendChild(listItem);
+}
+&lt;/textarea&gt;
+
+&lt;div class="playable-buttons"&gt;
+ &lt;input id="reset" type="button" value="Reset"&gt;
+ &lt;input id="solution" type="button" value="Show solution"&gt;
+&lt;/div&gt;
+</pre>
+
+<pre class="brush: css notranslate">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 notranslate">var textarea = document.getElementById('code');
+var reset = document.getElementById('reset');
+var solution = document.getElementById('solution');
+var code = textarea.value;
+var 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();
+});
+
+var jsSolution = 'var list = document.querySelector(\'.output ul\');\nlist.innerHTML = \'\';\nvar stations = [\'MAN675847583748sjt567654;Manchester Piccadilly\',\n \'GNF576746573fhdg4737dh4;Greenfield\',\n \'LIV5hg65hd737456236dch46dg4;Liverpool Lime Street\',\n \'SYB4f65hf75f736463;Stalybridge\',\n \'HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield\'];\n\nfor(var i = 0; i &lt; stations.length; i++) {\n var input = stations[i];\n var code = input.slice(0,3);\n var semiC = input.indexOf(\';\');\n var name = input.slice(semiC + 1);\n var result = code + \': \' + name;\n var listItem = document.createElement(\'li\');\n listItem.textContent = result;\n list.appendChild(listItem);\n}';
+var 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) {
+ var scrollPos = textarea.scrollTop;
+ var caretPos = textarea.selectionStart;
+
+ var front = (textarea.value).substring(0, caretPos);
+ var 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="結語">結語</h2>
+
+<p>不可否認當網站在跟人們互相溝通時,處理文字和句子在程式設計中是相當重要的,尤其是在 JavaScript 中。這篇文章已經傳授你如何去處理字串的方法,應該對以後深入了解其他更複雜主題的你會很有幫助。接下來,我們將會看看最後一個近期內我們需要關注的主要的資料型態 — 陣列。</p>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}</p>
+
+<h2 id="在這個學習模組中">在這個學習模組中</h2>
+
+<ul>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_is_JavaScript">什麼是 JavaScript?</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/A_first_splash">和 JavaScript 的第一次接觸</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_went_wrong">什麼出錯了? JavaScript 的疑難排解(除錯)</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Variables">儲存你需要的資訊 — 變數</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Math">JavaScript 的基本運算— 數字 與 運算子</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Strings">處理文字 — JavaScript 的字串</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Useful_string_methods">有用的字串方法</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Arrays">陣列</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Silly_story_generator">附錄:笑話產生器</a></li>
+</ul>
diff --git a/files/zh-tw/learn/javascript/first_steps/variables/index.html b/files/zh-tw/learn/javascript/first_steps/variables/index.html
new file mode 100644
index 0000000000..1fce3a98fe
--- /dev/null
+++ b/files/zh-tw/learn/javascript/first_steps/variables/index.html
@@ -0,0 +1,344 @@
+---
+title: 存儲您需要的資訊 - 變數
+slug: Learn/JavaScript/First_steps/Variables
+tags:
+ - JavaScript
+ - 變數
+ - 陣列
+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">閱讀完最後幾篇文章之後,您現在應該知道 JavaScript 是什麼,它可以為您做什麼,如何將它與其他 Web 技術一起使用,以及它的主要功能從高層看起來如何。 在本文中,我們將深入了解真正的基礎知識,了解如何使用 JavaScript 的大多數基本構建塊 - 變數。</p>
+
+<table class="learn-box">
+ <tbody>
+ <tr>
+ <th scope="row">必備知識:</th>
+ <td>電腦基礎知識,了解基本的 HTML 和 CSS ,了解 JavaScript 是什麼。</td>
+ </tr>
+ <tr>
+ <th scope="row">目標:</th>
+ <td>熟悉 JavaScript 變數的基本知識。</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="您需要的工具">您需要的工具</h2>
+
+<p>在此篇文章中,您將被要求輸入程式碼行來測試您對內容的理解。如果您使用的是網頁瀏覽器,最適合輸入代碼的地方便是 JavaScript 主控台, (請參閱<a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">什麼是瀏覽器開發工具</a>這篇文章以取得更多關於此工具的資訊).</p>
+
+<h2 id="什麼是變量/變數_variable_?">什麼是變量/變數 (variable) ?</h2>
+
+<p>變量是值的容器,就像我們可能在總和中使用的數字,或者我們可能用作句子一部分的字符串。 但關於變量的一個特殊之處在於它們包含的值可以改變。 我們來看一個簡單的例子:</p>
+
+<pre class="brush: html notranslate">&lt;button&gt;請按我&lt;/button&gt;
+</pre>
+
+<pre class="brush: js notranslate">const button = document.querySelector('button');
+
+button.onclick = function() {
+  let name = prompt('你叫什麼名字?');
+  alert('你好 ' + name + ', 很高興認識你!');
+}
+</pre>
+
+<p>{{ EmbedLiveSample('什麼是變量/變數_variable_?','100%', 50, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<p>在此示例中,按下按鈕會運行幾行代碼。 第一行在屏幕上彈出一個框,要求讀者輸入其名稱,然後將值存儲在變量中。 第二行顯示歡迎消息,其中包含從變量值中獲取的名稱。</p>
+
+<p>要理解為什麼這麼有用,讓我們考慮如何在不使用變量的情況下編寫此示例。 它最終會看起來像這樣:</p>
+
+<pre class="example-bad notranslate">let name = prompt('What is your name?');
+
+if (name === 'Adam') {
+ alert('Hello Adam, nice to see you!');
+} else if (name === 'Alan') {
+ alert('Hello Alan, nice to see you!');
+} else if (name === 'Bella') {
+ alert('Hello Bella, nice to see you!');
+} else if (name === 'Bianca') {
+ alert('Hello Bianca, nice to see you!');
+} else if (name === 'Chris') {
+ alert('Hello Chris, nice to see you!');
+}
+
+// ... 等等 ...
+</pre>
+
+<p><font>你可能暫時還沒有完全理解這些代碼和語法,但是你應該能夠理解到</font> — <font>如果我們沒有變量,我們就不得不寫大量的代碼去檢查輸入的名字,然後顯示相應名稱的消息 。這樣做顯然是低效率(雖然例子中只有5種選擇,但代碼卻相對地長)和不可行的</font> — <font>你沒有辦法列舉出所有可能的名字。</font></p>
+
+<p>使用變量才是明智的。隨著您對 JavaScript 越來越了解,您會開始習慣使用變量。</p>
+
+<p><font>變量的另一個特性就是它們能夠存儲任何的東西</font> — <font>不只是字符串和數字。變量可以存儲更複雜的數據,甚至是函數。</font><font>你將在後續的內容中體驗到這些用法。</font></p>
+
+<div class="note">
+<p><strong><font><font>提示</font></font></strong>:變量是用來儲存數值的,而變量和數值是兩個不同的概念。變量不是數值本身,它們僅僅是一個用於儲存數值的容器。你可以把變量想像成一個個用來裝東西的紙皮箱。</p>
+</div>
+
+<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="定義變量_Declaring_a_variable">定義<font><font>變量 (Declaring a variable)</font></font></h2>
+
+<p><font>要想使用變量,你需要做的第一步就是創建它</font> — <font>更準確的說,是</font>定義<font>一個變量。</font>定義<font>一個變量的語法是在關鍵字</font> <code>var</code> 或 <code>let</code> <font>之後加上變量的名字:</font></p>
+
+<pre class="brush: js notranslate">let myName;
+let myAge;
+</pre>
+
+<p><font><font>在這裡我們</font></font>定義<font><font>了兩個變量  </font></font><code>myName</code><font><font> 和 </font></font><code>myAge</code><font><font>。那麼現在嘗試輸入這些代碼到你的瀏覽器終端。之後,嘗試使用您自己選擇的名稱來創建一兩個變量。</font></font></p>
+
+<div class="note">
+<p><strong>提示</strong>:<font><font>在 JavaScript 中,所有代碼指令都會以分號結尾( </font></font><code>;</code><font><font>)- 如果忘記加分號,你的單行代碼可能正常執行,但是在執行多行代碼的時候就可能出錯。所以,最好是養成主動以分號作為代碼結尾的習慣。</font></font></p>
+</div>
+
+<p><font>你可以輸入變量的名稱,來驗證這個變量的數值是否在執行環境(</font>execution environment)<font>中已經存在。例如,</font></p>
+
+<pre class="brush: js notranslate">myName;
+myAge;
+</pre>
+
+<p><font><font>以上這兩個變量並沒有數值,他們是空的容器。當你輸入變量名並按輸入鍵後,你會得到一個 </font></font><code>undefined</code><font><font> (</font></font>沒有定義的值<font><font>)的返回值。如果</font>變量<font>並不存在的話,你就會得到一個錯誤信息。請嘗試輸入:</font></font></p>
+
+<pre class="brush: js notranslate">scoobyDoo;</pre>
+
+<div class="note">
+<p><strong><font><font>提示:</font></font></strong><font><font>千萬不要把兩個概念弄混淆了,「一個變量<strong>存在,但是沒有數值</strong>」和「一個變量<strong>並不存在</strong>」— 他們完全是兩回事。在前面你看到的盒子的類比中,不存在意味著沒有可以存放變量的「盒子」。</font><font>沒有定義的值意味著<strong>有</strong>一個「盒子」,但是它裡面沒有任何數值。</font></font></p>
+</div>
+
+<h2 id="初始化變量_Initializing_a_variable">初始化變量 (Initializing a variable)</h2>
+
+<p>一旦你定義了一個變量,你就能夠初始化它來儲存數值。方法如下:在變量名之後跟上一個等號 (<code>=</code>),然後是數值。例如:</p>
+
+<pre class="brush: js notranslate">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 notranslate">myName;
+myAge;</pre>
+
+<p>你可以同時定義並初始化變量,像是:</p>
+
+<pre class="brush: js notranslate">let myDog = 'Rover';</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>
+
+<h2 id="比較var和let的不同_The_difference_between_var_and_let">比較var和let的不同 (The difference between var and let)</h2>
+
+<p>此刻你或許會思考「為什麼我們需要兩種方法來定義變數??<font><font>」</font></font>「為甚麼要有<code>var</code>和<code>let</code>??<font><font>」</font></font></p>
+
+<p>原因有些歷史淵源。在Javascript剛被創造的時候,只有<code>var</code>可以使用。在大部分的情況下都很正常,但是<code>var</code>的運作方式有些問題 — 它的設計有時會令人困惑甚至惹惱人。所以<code>let</code>在現代版本中的Javascript被創造出來,一個與<code>var</code>工作原理有些不同的創建變數的關鍵字,修復了<code>var</code>的種種問題。</p>
+
+<p>以下將介紹幾個簡單的分別。我們現在不會一一講解全部的不同,但是當你慢慢深入Javascript,你將會開始發現它們的(如果你真的很想現在知道,歡迎看看我們的<a href="/zh-TW/docs/Web/JavaScript/Reference/Statements/let">let 介紹頁</a>)。</p>
+
+<p>如下,假設你需要宣告、初始化一個變數<code>myName</code>,即使你是初始化之後才宣告也是可行的:</p>
+
+<pre class="brush: js notranslate">myName = 'Chris';
+
+function logName() {
+ console.log(myName);
+}
+
+logName();
+
+var myName;</pre>
+
+<div class="note">
+<p><strong>Note</strong>: This won't work when typing individual lines into a JavaScript console, just when running multiple lines of JavaScript in a web document.</p>
+</div>
+
+<p>This works because of <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>
+
+<p>Hoisting no longer works with <code>let</code>. If we changed <code>var</code> to <code>let</code> in the above example, it would fail with an error. This is a good thing — declaring a variable after you initialize it makes for confusing, harder to understand code.</p>
+
+<p>Secondly, when you use <code>var</code>, you can declare the same variable as many times as you like, but with <code>let</code> you can't. The following would work:</p>
+
+<pre class="brush: js notranslate">var myName = 'Chris';
+var myName = 'Bob';</pre>
+
+<p>But the following would throw an error on the second line:</p>
+
+<pre class="brush: js notranslate">let myName = 'Chris';
+let myName = 'Bob';</pre>
+
+<p>You'd have to do this instead:</p>
+
+<pre class="brush: js notranslate">let myName = 'Chris';
+myName = 'Bob';</pre>
+
+<p>Again, this is a sensible language decision. There is no reason to redeclare variables — it just makes things more confusing.</p>
+
+<p>For these reasons and more, we recommend that you use <code>let</code> as much as possible in your code, rather than <code>var</code>. There is no reason to use <code>var</code>, unless you need to support old versions of Internet Explorer with your code (it doesn't support <code>let</code> until version 11; the modern Windows Edge browser supports <code>let</code> just fine).</p>
+
+<div class="note">
+<p><strong>Note</strong>: We are currently in the process of updating the course to use <code>let</code> rather than <code>var</code>. Bear with us!</p>
+</div>
+
+<h2 id="Updating_a_variable">Updating a variable</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 notranslate">myName = 'Bob';
+myAge = 40;</pre>
+
+<h3 id="變數命名規則悄悄話">變數命名規則悄悄話</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>良好的命名範例:</p>
+
+<pre class="example-good notranslate">age
+myAge
+init
+initialColor
+finalOutputValue
+audio1
+audio2</pre>
+
+<p>不好的命名範例:</p>
+
+<pre class="example-bad notranslate">1
+a
+_12
+myage
+MYAGE
+var
+Document
+skjfndskjfnbdskjfb
+thisisareallylongstupidvariablenameman</pre>
+
+<p>Error-prone name examples:</p>
+
+<pre class="example-invalid notranslate">var
+Document
+</pre>
+
+<p>Try creating a few more variables now, with the above guidance in mind.</p>
+
+<h2 id="變數資料類型">變數資料類型</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 notranslate">let 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 notranslate">let 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 notranslate">let iAmAlive = true;</pre>
+
+<p>Whereas in reality it would be used more like this:</p>
+
+<pre class="brush: js notranslate">let test = 6 &lt; 3;</pre>
+
+<p>This is using the "less than" operator (<code>&lt;</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 它包含多個用方括號括起來並用逗號分隔的值。Try entering the following lines into your console:</p>
+
+<pre class="brush: js notranslate">let myNameArray = ['Chris', 'Bob', 'Jim'];
+let 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 notranslate">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 href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">a future article</a>.</p>
+
+<h3 id="Objects_物件">Objects 物件</h3>
+
+<p>在編程中,物件是對真實生活物件進行建模的代碼結構。 您可以擁有一個代表停車場的簡單物件,其中包含有關其寬度和長度的信息,或者您可以擁有一個代表一個人的物件,並用物件紀錄其姓名、身高、體重、慣用語言,如何跟他打招呼等的資訊。</p>
+
+<p>請試著在你的console中輸入以下指令:</p>
+
+<pre class="brush: js notranslate">let dog = { name : 'Spot', breed : 'Dalmatian' };</pre>
+
+<p>取得物件中儲存的資料可以使用以下語法:</p>
+
+<pre class="brush: js notranslate">dog.name</pre>
+
+<p>We won't be looking at objects any more for now — you can learn more about those in <a href="/en-US/docs/Learn/JavaScript/Objects">a future module</a>.</p>
+
+<h2 id="動態型別">動態型別</h2>
+
+<p>JavaScript 是一個"動態型別語言",意思是不像其他強型別程式語言,在JavaScript 宣告變數時你不用指定指定資料類型(數字、字串或陣列等等)。</p>
+
+<p>For example, if you declare a variable and give it a value enclosed in quotes, the browser will treat the variable as a string:</p>
+
+<pre class="brush: js notranslate">let myString = 'Hello';</pre>
+
+<p>It will still be a string, even if it contains numbers, so be careful:</p>
+
+<pre class="brush: js notranslate">let 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><a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a></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="JavaScript中的常數">JavaScript中的常數</h2>
+
+<p>許多程式語言都有常數的概念:一經宣告就不改變的值。設定常數有許多原因,例如若引入第三方腳本而改動變數值,將會造成許多問題而且很難除錯。</p>
+
+<p>一開始JavaScript是沒有常數的,直到今日我們才有了關鍵字 <code>const</code>,讓我們儲存不能改變的值:</p>
+
+<pre class="brush: js notranslate">const daysInWeek = 7<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-number">;
+const hoursInDay = 24;</span></span></span></span></pre>
+
+<p><span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-number"><code>const</code> works in exactly the same way as <code>let</code>, except that you can't give a <code>const</code> a new value. In the following example, the second line would throw an error:</span></span></span></span></p>
+
+<pre class="brush: js notranslate">const daysInWeek = 7<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-number">;
+daysInWeek = 8;</span></span></span></span></pre>
+
+<h2 id="Summary">Summary</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="在這個學習模組中">在這個學習模組中</h2>
+
+<ul>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_is_JavaScript">什麼是 JavaScript?</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/A_first_splash">和 JavaScript 的第一次接觸</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_went_wrong">什麼出錯了? JavaScript 的疑難排解(除錯)</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Variables">儲存你需要的資訊 — 變數</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Math">JavaScript 的基本運算— 數字 與 運算子</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Strings">處理文字 — JavaScript 的字串</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Useful_string_methods">有用的字串方法</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Arrays">陣列</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Silly_story_generator">附錄:笑話產生器</a></li>
+</ul>
diff --git a/files/zh-tw/learn/javascript/first_steps/what_is_javascript/index.html b/files/zh-tw/learn/javascript/first_steps/what_is_javascript/index.html
new file mode 100644
index 0000000000..c610e17dd8
--- /dev/null
+++ b/files/zh-tw/learn/javascript/first_steps/what_is_javascript/index.html
@@ -0,0 +1,425 @@
+---
+title: JavaScript 是什麼?
+slug: Learn/JavaScript/First_steps/What_is_JavaScript
+tags:
+ - API
+ - 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">歡迎來到 MDN 的 JavaScript 初學者課程!我們將在這個章節綜觀 JavaScript ,回答一些像是「它什麼?」和「可以使用它作什麼?」之的問題,並確保你了解 JavaScript 的特性。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">先備條件:</th>
+ <td>基本的電腦知識,基本了解 HTML 和 CSS 技術。</td>
+ </tr>
+ <tr>
+ <th scope="row">學習目標:</th>
+ <td>了解 JavaScript 的本質、功能、以及它如何構成網站的一部分</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="高層次的定義">高層次的定義</h2>
+
+<p>JavaScript 是一種腳本,也能稱它為程式語言,可以讓你在網頁中實現出複雜的功能。當網頁不只呈現靜態的內容,另外提供了像是:內容即時更新、地圖交動、繪製 2D/3D 圖形,影片播放控制……等,你就可以大膽地認為 JavaScript 已經參與其中。它是標準網頁技術蛋糕的第三層,而其他兩層(<a href="/zh-TW/docs/Learn/HTML">HTML</a> 和 <a href="/zh-TW/docs/Learn/CSS">CSS</a>)我們在其他學習單元中有更多詳細的介紹。</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13502/cake.png" style="display: block; margin: 0 auto;"></p>
+
+<ul>
+ <li>{{glossary("HTML")}} 是一種標記語言,我們使用它組織網頁裡的內容並給予定義, 例如:定義段落、標題、資料表格,或是在頁面嵌入圖片和影片。.</li>
+ <li>{{glossary("CSS")}} 是一種樣式規則的語言,用來幫我們的 HTML 內容上套用樣式,例如:設置背景顏色、字型,或讓內容以多欄的方式呈現。</li>
+ <li>{{glossary("JavaScript")}} 是一種腳本語言,它使你能夠動態的更新內容、控制多媒體、動畫……幾乎所有事。(好吧,不是所有事情,但神奇的是你可以通過短短幾行 JavaScript 程式碼實現。)</li>
+</ul>
+
+<p>這三層很好的構建在一起。讓我們以一個簡單的文字為例。我們可以使用 HTML 標記來表示它的結構和意圖:</p>
+
+<pre class="brush: html notranslate">&lt;p&gt;Player 1: Chris&lt;/p&gt;</pre>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13422/just-html.png" style="height: 28px; width: 108px;"></p>
+
+<p>然後我們可以加一些 CSS ,讓它看起來更好:</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>最後,我們可以加一些  JavaScript 來作出互動的行為:</p>
+
+<pre class="brush: js notranslate">const para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+ let name = prompt('輸入新的名字');
+ para.textContent = 'Player 1: ' + name;
+}
+</pre>
+
+<p>{{ EmbedLiveSample('高層次的定義', '100%', 80, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<p>試試點擊這最後版本的文字,看看會發生什麼事情(你同樣也可以在 GitHub 找到這個範例,來查看<a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/what-is-js/javascript-label.html">原始碼</a>或<a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/what-is-js/javascript-label.html">在線上執行</a>)!</p>
+
+<p>JavaScript 能做到更多,讓我們更深入地探索。</p>
+
+<h2 id="它究竟可以做什麼呢">它究竟可以做什麼呢?</h2>
+
+<p>JavaScript 語言的核心包含了很多常用的程式功能供你使用,如:</p>
+
+<ul>
+ <li>將有用的值存儲在變數中。例如上述例子,我們要求輸入一個新名字,然後將該名字存在名為<code>name</code>的變數裡。</li>
+ <li>對文本片段的操作(在程式裡稱作"字串")。在上述例子中,我們拿了字串 "Player 1: " 並將其與 <code>name</code> 變數連接來創造完整文本標籤,如:''Player 1: Chris"。</li>
+ <li>執行程式碼,回應網頁上發生的某些事件。在上述例子中,我們使用 {{Event("click")}} 事件,當按鈕被點擊時,便執行更新文本標籤的程式碼。 </li>
+ <li>以及其他更多更多的功能!</li>
+</ul>
+
+<p>然而,更令人興奮的是那些基於用戶端的 JavaScript 語言構建的功能。也就是所謂的 <strong>應用程式介面</strong>(<strong>API</strong>),提供 JavaScript 程式額外的超能力。</p>
+
+<p>API 是預先製作完成的程式模組,支援開發者實現困難或無法實現的功能。在程式設計中就如同在建築房子的時候使用系統傢俱,拿預先裁好的板子用螺絲鎖上來組合成書架,相比從頭自己設計,找合適木材,切成正確的形狀和尺寸,再找到合適的螺絲最後組裝書架而言更簡單。</p>
+
+<p>他們通常分為兩類。</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>瀏覽器 API(Browser APIs)</strong>內建在你的瀏覽器中,能夠依本地的電腦環境輸出資料或實現複雜的功能。舉例而言:</p>
+
+<ul>
+ <li>{{domxref("Document_Object_Model","DOM (文件物件模型) API")}} 讓你能操作 HTML和 CSS,像是建立、移除或改變 HTML 元素,或動態地將新樣式套用到頁面…等等。每當你看到彈出視窗,或有新的內容出現在畫面上(就像上面的範例所展示的),那就是 DOM 在動作。</li>
+ <li>{{domxref("Geolocation","Geolocations(地理位置) API")}} 可以取得位置資訊。這就是 <a href="https://www.google.com/maps">Google Maps</a> 取得你的位置並標示在地圖上所透過的方式。</li>
+ <li>{{domxref("Canvas_API","Canvas")}} 和 {{domxref("WebGL_API","WebGL")}} API 可以讓你在網頁創造 2D 動畫及 3D 圖像。人們正使用這些技術來作一些令人驚奇的事,參見 <a href="https://www.chromeexperiments.com/">Chrome Experiments</a> 及 <a href="http://webglsamples.org/">webglsamples</a>.</li>
+ <li><a href="https://developer.mozilla.org/zh-TW/Apps/Fundamentals/Audio_and_video_delivery">Audio 和 Video API</a> 像 {{domxref("HTMLMediaElement")}} 和  {{domxref("WebRTC API", "WebRTC")}} 一樣讓你可以使用多媒體做真正有趣的事情,例如在網頁中播放音樂或影片,或由網路攝影機頡取你的影像顯示在另一個人電腦裡(試試我們的<a href="http://chrisdavidmills.github.io/snapshot/">簡單例子</a>來了解)。</li>
+</ul>
+
+<div class="note">
+<p><strong>注意</strong>:上面的許多範例無法在舊版的瀏覽器上運作。使用現代的瀏覽器像是 Firefox、Chrome、Edge 或 Opera 來嘗試執行你的程式總是比較好的。當你接近要交付作為產品的程式(也就是實際的用戶將要使用的時候),就需要思考關於<a href="/zn-TW/docs/Learn/Tools_and_testing/Cross_browser_testing">跨瀏覽器測試</a>的事情。</p>
+</div>
+
+<p><strong>第三方 API</strong> 預設不內建在瀏覽器裡,你通常由網路上取得他們的程式碼與資訊。例如:</p>
+
+<ul>
+ <li><a href="https://dev.twitter.com/overview/documentation">Twitter API</a> 能讓你做很多事,像是顯示最新的Twitter貼文在你的網站上。</li>
+ <li><a href="https://developers.google.com/maps/">Google Maps API</a> 能讓你在自己的網站中嵌入訂製的地圖或其他相關功能。</li>
+</ul>
+
+<div class="note">
+<p><strong>注意</strong>: 我們不會在此涵蓋這些進階的APIs。你可以在我們的 <a href="/zh-TW/docs/Learn/JavaScript/Client-side_web_APIs">客戶端網頁 API 單元</a>找到更多資訊。</p>
+</div>
+
+<p>那裡也有很多的東西。然而不要一頭熱陷進去。你不會在學習 JavaScript 24 小時後,就能開發出下一個 Facebook、Google 地圖或 Instagram 之類的產品出來。有許多的基礎的東西得先了解,這也是你在這裡的原因,讓我們繼續吧!</p>
+
+<h2 id="JavaScript_在你的頁面做了些什麼?">JavaScript 在你的頁面做了些什麼?</h2>
+
+<p>這裡我們開始看一些程式碼,探索當 JavaScript 在你的頁面上執行時,發生了哪些事情。</p>
+
+<p>簡單回顧一下當瀏覽器載入一個網站時會發生的事情(第一次是在我們的<a href="/zh-TW/Learn/CSS/Introduction_to_CSS/How_CSS_works#How_does_CSS_actually_work">CSS 如何工作</a>章節中提到)。當瀏覽器載入一個網頁,就是在執行環境(瀏覽器分頁)中執行程式碼(HTML,CSS 和 JavaScript)。就像是工廠收集原料(程式碼)並且產出商品(網頁呈現的結果)。</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13504/execution.png" style="display: block; margin: 0 auto;"></p>
+
+<p>透過 DOM API (上面提到的)動態調整 HTML 與 CSS 進行改變網頁呈現,在 JavaScript 是很常見的使用方式。要注意的是,檔案中的程式碼通常會以出現在頁面上的順序來執行。如果 JavaScript 比準備操作的 HTML 、 CSS 更早被載入,就可能會發生錯誤。你將會在這個章節的後段學到一些解決問題的方法,它在<a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_is_JavaScript#Script_loading_strategies">腳本載入策略</a>的部分。</p>
+
+<h3 id="瀏覽器安全性">瀏覽器安全性</h3>
+
+<p>瀏覽器的每個分頁有獨立的空間來執行程式碼(技術上稱「執行環境excution environments」),這表示在絕大部分的情形之下,每個分頁的程式碼是獨立運行的,不能直接影響其它分頁(或網站)裡的程式。這是一個好的安全措施,少了它,有心人會開始寫程式來偷取網站的資料,或是作其它不好的事情。</p>
+
+<div class="note">
+<p><strong>注意</strong>:是有一些安全的方式能在不同的網頁、分頁之間傳遞程式和資料,不過這些進階的技術不會在涵蓋在這個單元中。</p>
+</div>
+
+<h3 id="JavaScript_的執行順序">JavaScript 的執行順序</h3>
+
+<p>當瀏覽器遇到一段 JavaScript 程式碼,通常會由上到下執行。這意味著你需要注意東西擺放的順序。為了說明,讓我們回到我們曾看過的第一個範例:</p>
+
+<pre class="brush: js notranslate">const para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+ let name = prompt('輸入新的名字');
+ para.textContent = 'Player 1: ' + name;
+}</pre>
+
+<p>這裡我們選擇了一個文字段落(第 1 行),然後加上事件偵聽器,所以當段落被點擊的時候,<code>updateName()</code> 程式區塊(5 到 8 行 )會被執行。<code>updateName()</code> 程式區塊(這種可以重複使用的程式區塊被稱為「函數 function」)會向使用者要一個新的名字,然後將插到段落中,更新顯示的內容。</p>
+
+<p>如果你交換前兩行的程式碼,它將不再正常運作。取而代之的,<a href="/zh-TW/docs/Learn/Common_questions/What_are_browser_developer_tools">瀏覽器開發主控台</a>會回報一個錯誤訊息:「<code>TypeError: para is undefined</code>」,意思是 <code>para</code> 物件尚不存在,所以我們在它上頭增加事件偵聽器。</p>
+
+<div class="note">
+<p><strong>注意</strong>: 這是一個很常見的錯誤,在你嘗試對物件進行操作之前,你需要注意它們已經存在。</p>
+</div>
+
+<h3 id="直譯式與編譯式程式語言">直譯式與編譯式程式語言</h3>
+
+<p>你可能在程式相關的文章中看過<strong>直譯式</strong> (<strong>interpreted</strong> )與<strong>編譯式 (compiled)</strong>這兩個詞。在直譯式程式語言中,程式碼由上到下執行,而且執行的結果是立即回應得到的。在瀏覽器執行前,你不需要將程式轉換為其它的形式。程式碼的內容是以對程式人員友善的形式並直接能夠運作。</p>
+
+<p>另一方面,編譯式程式語言需要在電腦執行之前轉換(編譯)成另一種形式。例如: C/C++ 在被電腦執行之前要編譯為組合語言。被執行的程式是一種二進位的格式,由程式原始碼產生出來。</p>
+
+<p>JavaScript 是一個輕量的直接程式語言。網頁瀏覽器收到文字格式的 JavaScript 程式碼,並直接執行。以技術的角度來看,大多數現代的 JavaScript 直譯器實際上會使用一種稱為<strong>即時編譯(just-in-time compiling)</strong>的技術來提升執行表現。 JavaScript 被使用時,原始程式會被編譯成更快的二進位格式,讓它們能更有效率的運行。然而, JavaScript 仍然被認為是一種直譯式的程式語言,因為編譯動作是在程式運作時,而不是事先完成。</p>
+
+<p>兩種語言都有各自的優點,但是我們不在此時討論這個議題。</p>
+
+<h3 id="伺服器端與用戶端程式">伺服器端與用戶端程式</h3>
+
+<p>你也有可能聽過<strong>伺服器端</strong>與<strong>客戶端</strong>程式,尤其在網站開發的領域。客戶端程式在使用者的電腦中運作,當瀏覽網頁的時候,頁面中的客戶端程式被下載,接著被瀏覽器執行與顯示結果。在這個單元中,我們只談論<strong>客戶端 JavaScript</strong>。</p>
+
+<p>另一方面,伺服器端的程式在伺服器上執行,接著產出的結果被瀏覽器下載後顯示。受歡迎的伺服器端網頁語言,包括 PHP、Python、Ruby 和 ASP.NET 以及… JavaScript!JavaScript 也能夠作為伺服器端程式語言,流行的 Node.js 環境就是一例。你可以在我們的<a href="/zh-TW/docs/Learn/Server-side">動態網站—伺服器端網站程式設計</a>主題中找到更多資訊。</p>
+
+<h3 id="動態與靜態程式">動態與靜態程式</h3>
+
+<p><strong>動態</strong>一詞被用於描述用戶端 JavaScript 和伺服器端程的式語言,用來描述具有在不同的狀況下更新網頁/網頁應用程式來顯示不同東西,依需要來產生新內容的能力。是根據要求生成新內容的能力。伺服器端程式在伺服器上動態產生的新內容,可能是來自資料庫中取出的數據,而用戶端 JavaScript 在收到由伺服器端要回來的資料,在瀏覽器內動態產生新的內容(如 HTML 表格)後加入頁面中呈現出來。在兩個情境中詞義稍微不同,但是相關的,兩種方法(伺服器端和用戶端)通常可以協同工作。</p>
+
+<p>一個沒有動態更新內容能力的網頁被稱為<strong>靜態</strong>,它在任何時候都只顯示一樣的內容。</p>
+
+<h2 id="如何在網頁中增加_JavaScript_?">如何在網頁中增加 JavaScript ?</h2>
+
+<p>在 HTML 頁面中使用 JavaScript 與 CSS 的方法類似。在 HTML 中 CSS 藉著{{htmlelement("link")}} 元素引入外部樣式(stylesheets)以及 {{htmlelement("style")}} 元素定義內部樣式。JavaScript 在 HTML中只需要一個朋友 — {{htmlelement("script")}} 元素。讓我們了解它是如何運作。</p>
+
+<h3 id="內部的_JavaScript">內部的 JavaScript</h3>
+
+<ol>
+ <li>首先,下載一份 <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>儲存在自己的電腦上合適的目錄裡。</li>
+ <li>用瀏覽器與文字編輯器打開範例。你會看到 HTML 建立了一個簡單的網頁,包含一個可點擊的按鈕。</li>
+ <li>接著,切換到文字編輯器,在標頭區加入下面的文字,就放在 <code>&lt;/head&gt;</code> 結尾標籤前:
+ <pre class="brush: html notranslate">&lt;script&gt;
+
+ // JavaScript 將放在這裡
+
+&lt;/script&gt;</pre>
+ </li>
+ <li>現在,我們將在我們的 {{htmlelement("script")}} 元素中加入一些 JavaScript 程式,讓網頁能做些有趣的事,接者在「// JavaScript 將放在這裡」那行後面:
+ <pre class="brush: js line-numbers language-js notranslate"><code class="language-js">document<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">"DOMContentLoaded"</span><span class="punctuation token">,</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ <span class="keyword token">function</span> <span class="function token">createParagraph</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ <span class="keyword token">let</span> para <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">createElement</span><span class="punctuation token">(</span><span class="string token">'p'</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
+ para<span class="punctuation token">.</span>textContent <span class="operator token">=</span> <span class="string token">'You clicked the button!'</span><span class="punctuation token">;</span>
+ document<span class="punctuation token">.</span>body<span class="punctuation token">.</span><span class="function token">appendChild</span><span class="punctuation token">(</span>para<span class="punctuation token">)</span><span class="punctuation token">;</span>
+ <span class="punctuation token">}</span>
+
+ <span class="keyword token">const</span> buttons <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">querySelectorAll</span><span class="punctuation token">(</span><span class="string token">'button'</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
+
+ <span class="keyword token">for</span><span class="punctuation token">(</span><span class="keyword token">let</span> i <span class="operator token">=</span> <span class="number token">0</span><span class="punctuation token">;</span> i <span class="operator token">&lt;</span> buttons<span class="punctuation token">.</span>length <span class="punctuation token">;</span> i<span class="operator token">++</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ buttons<span class="punctuation token">[</span>i<span class="punctuation token">]</span><span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">'click'</span><span class="punctuation token">,</span> createParagraph<span class="punctuation token">)</span><span class="punctuation token">;</span>
+ <span class="punctuation token">}</span>
+<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre>
+ </li>
+ <li>儲存你的檔案並且重新整理網頁,現在你會發現每次點擊按鈕,都會在下方產生一個新的文字段落。</li>
+</ol>
+
+<div class="note">
+<p><strong>注意</strong>: 如果你的版本不能正常運作,重新按照步驟再操作一次,檢查每一步都正確。你下載的範例是 <code>.html</code> 結尾的檔名?你加入的 {{htmlelement("script")}} 元素在 <code>&lt;/head&gt;</code> 標籤的前面?你輸入的 JavaScript 與上面提供的一模一樣? <strong>JavaScript 程式大小寫,而且很挑剔,所以你輸入的語法要一模一樣,不然可能會無法運作。</strong></p>
+</div>
+
+<div class="note">
+<p><strong>注意</strong>: GitHub上有完整版本的範例在 <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">看線上版本</a>)。</p>
+</div>
+
+<h3 id="外部的_JavaScript">外部的 JavaScript</h3>
+
+<p>內部 JavaScript 目前運作得很好,但如果我們想把 JavaScript 放在外部檔案,應該怎麼做?讓我們現在來探索。</p>
+
+<ol>
+ <li>首先,建立一個新的檔案,和 HTML 檔案放在相同的目錄下,命名為 <code>script.js</code> ,確定這個檔案是以 .js 為副檔名, 因為這就是它被識別為 JavaScript 的原因。</li>
+ <li>將 {{htmlelement("script")}} 元素(包含裡面的程式)換成下面的樣子:
+ <pre class="brush: html notranslate">&lt;script src="script.js" async&gt;&lt;/script&gt;</pre>
+ </li>
+ <li>在 <code>script.js</code> 中,加入下面的程式碼:
+ <pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="keyword token">function</span> <span class="function token">createParagraph</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ <span class="keyword token">let</span> para <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">createElement</span><span class="punctuation token">(</span><span class="string token">'p'</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
+ para<span class="punctuation token">.</span>textContent <span class="operator token">=</span> <span class="string token">'You clicked the button!'</span><span class="punctuation token">;</span>
+ document<span class="punctuation token">.</span>body<span class="punctuation token">.</span><span class="function token">appendChild</span><span class="punctuation token">(</span>para<span class="punctuation token">)</span><span class="punctuation token">;</span>
+<span class="punctuation token">}</span>
+
+<span class="keyword token">const</span> buttons <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">querySelectorAll</span><span class="punctuation token">(</span><span class="string token">'button'</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
+
+<span class="keyword token">for</span><span class="punctuation token">(</span><span class="keyword token">let</span> i <span class="operator token">=</span> <span class="number token">0</span><span class="punctuation token">;</span> i <span class="operator token">&lt;</span> buttons<span class="punctuation token">.</span>length <span class="punctuation token">;</span> i<span class="operator token">++</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ buttons<span class="punctuation token">[</span>i<span class="punctuation token">]</span><span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">'click'</span><span class="punctuation token">,</span> createParagraph<span class="punctuation token">)</span><span class="punctuation token">;</span>
+<span class="punctuation token">}</span></code></pre>
+ </li>
+ <li>儲存檔案並在你的瀏覽器執行重新整理,你應該會看到一樣的結果!雖然是一樣的結果,但現在我們是由外部的檔案來引入 JavaScript 程式。就組織程式碼,讓程式可以在多個 HTML 間重複被使用而言,這通常是好的作法。另外,因為少了一大堆程式碼在裡頭,也能夠讓 HTML 檔案更容易被閱讀。</li>
+</ol>
+
+<div class="note">
+<p><strong>注意</strong>: 你可以在 GitHub 上找到這個版本的 <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> 與 <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">看線上版本</a>)。</p>
+</div>
+
+<h3 id="行內的_JavaScript">行內的 JavaScript</h3>
+
+<p>注意,有時候你會遇到一些 JavaScript 程式混在HTML語法之中。它可能會看起來像這樣:</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">&lt;button onclick="createParagraph()"&gt;Click me!&lt;/button&gt;</pre>
+
+<p>你可以在底下試試這個段程式的作用。</p>
+
+<p>{{ EmbedLiveSample('行內的_JavaScript', '100%', 150, "", "", "hide-codepen-jsfiddle") }}</p>
+
+<p>這個範例與前面兩個有完全相同的功能,除了 {{htmlelement("button")}} 元素中包含了一個行內 <code>onclick</code> 處理程序,當按鈕按下時執行。</p>
+
+<p><strong>然而,請不要這樣做。</strong>用 JavaScript 汙染你的 HTML 是一種不好的作法,而且沒有效率,因為你必須在每個你希望 JavaScript 作用的地方加入 <code>onclick="createParagraph()"</code> 屬性。</p>
+
+<p>使用單純 JavaScript 的結構,讓你可以用一個指令選擇所有的按鈕。在我們前面的範例中,使用下面的程式碼達到這個目的:</p>
+
+<pre class="notranslate">var buttons = document.querySelectorAll('button');
+
+for (var i = 0; i &lt; buttons.length ; i++) {
+ buttons[i].addEventListener('click', createParagraph);
+}</pre>
+
+<p>這或許看起來比 <code>onclick</code> 屬性還長一點,但是能套用在全部的按鈕上,無論頁面上有多少按鈕,也不管未來新增或移除多少個(按鈕)。這段 JavaScript 程式都不需要改變。</p>
+
+<div class="note">
+<p><strong>注意</strong>: 試著編輯你自己版本的 <code>apply-javascript.html</code> ,在裡面多添加一點按鈕。當你重新載入網頁,你應該會發現所有按鈕,按下去的時候都會建立一的段落。很簡潔吧!</p>
+</div>
+
+<h3 id="腳本載入策略Script_loading_strategies">腳本載入策略(Script loading strategies)</h3>
+
+<p>在正確的時機載入腳本涉及一些要注意的東西。並不如它看起來的簡單!其中一個常見的問題是,所有的 HTML 是根據出現順序載入。假如你使用 JavaScript 操作頁面中的元素(精確地來說是 <a href="/zh-TW/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents#The_document_object_model">DOM 元素</a>),如果 JavaScript 在這些 HTML 操作對象前被讀取及解析,你的程式將無法運作。</p>
+
+<p>上面的範例中,內部和外部 JavaScript 範例裡的程式碼都放在 HTML 的 head 區域,在 body 區被載入前就先被解析。這樣會造成一些問題,所以我們載入與執行在文件(HTML檔)的開頭,是HTML <code>body</code> 還沒解析之前。這可能會產生錯誤,所以我們使用一些模式來處理它。</p>
+
+<p>在內部程式的範例中,你可以看到以下這樣結構的程式碼:</p>
+
+<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">document<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">"DOMContentLoaded"</span><span class="punctuation token">,</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
+ <span class="operator token">...</span>
+<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre>
+
+<p>這是一個事件偵聽器,它偵聽瀏覽器的「DOMContentLoaded」事件,它是在 HTML body 部分已經完全載入與解析發出。區塊內(... 的部分)的 JavaScript 直到事件被發出後才會執行,這樣子問題就被避開了。(你將會在這個課程中<a href="/zh-TW/docs/Learn/JavaScript/Building_blocks/Events">學習到什麼是事件</a>)</p>
+
+<p>在外部程式的範例中,我們使用比較現代的 JavaScript 特性來解決這個問題,<code>defer</code> 屬性,它告訴瀏覽器碰到這種 <code>&lt;script&gt;</code> 標籤時,繼續下載後面其他的 HTML 內容。</p>
+
+<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="operator token">&lt;</span>script src<span class="operator token">=</span><span class="string token">"script.js"</span> defer<span class="operator token">&gt;</span><span class="operator token">&lt;</span><span class="operator token">/</span>script<span class="operator token">&gt;</span></code></pre>
+
+<p>在這個例子中,腳本(JavaScript 程式)與 HTML 會同時載入,所以程式將正確地執行。</p>
+
+<div class="note">
+<p><strong>注意</strong>: 在外部程式的範例裡,我們不需要使用 <code>DOMContentLoaded</code> 事件因為 <code>defer</code> 為我們解決問題了。而在內部程式的範例裡我們沒用 <code>defer</code> 屬性,是因為 <code>defer</code> 屬性只能用於外部的腳本。</p>
+</div>
+
+<p>這個問題有另一個舊式的解決方法,就是將 <code>script</code> 元素放在 <code>body</code> 元素的底部(剛好在 <code>&lt;/body&gt;</code> 的前面),如此它就會在所有 HTML 被解析完之後才被載入。這個方法的問題在於腳本的載入與解析工作會被完成擋住,一直到所有 HTML 載入完成。在擁有許多 JavaScript 的大型網站中,這樣會導致嚴重的效能問題,拖慢你的網站。</p>
+
+<h4 id="async_和_defer">async 和 defer</h4>
+
+<p>實際上,有兩個方法可以閃過上述腳本被擋到的問題:<code>async</code> 與 <code>defer</code>(前面看到的)。來看看兩者的區別。</p>
+
+<p>使用 <code>async</code> 屬性(如下所示)所載入的腳本,在下載的同時不會讓網頁的渲染被阻塞(停住),並且在下載完成後馬上執行。它並不保證腳本會按照任何特定的順序執行,只保證不去妨礙網頁中其他部分顯示工作。<code>async</code> 的最佳使用情境,是當網頁中的腳本間彼此獨立,因而不依賴彼此運行的狀況下。</p>
+
+<p>例如你有以下的 <code>script</code> 元素</p>
+
+<pre class="brush: html line-numbers language-html notranslate"><code class="language-html"><span class="tag token"><span class="tag token"><span class="punctuation token">&lt;</span>script</span> <span class="attr-name token">async</span> <span class="attr-name token">src</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>js/vendor/jquery.js<span class="punctuation token">"</span></span><span class="punctuation token">&gt;</span></span><span class="tag token"><span class="tag token"><span class="punctuation token">&lt;/</span>script</span><span class="punctuation token">&gt;</span></span>
+
+<span class="tag token"><span class="tag token"><span class="punctuation token">&lt;</span>script</span> <span class="attr-name token">async</span> <span class="attr-name token">src</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>js/script2.js<span class="punctuation token">"</span></span><span class="punctuation token">&gt;</span></span><span class="tag token"><span class="tag token"><span class="punctuation token">&lt;/</span>script</span><span class="punctuation token">&gt;</span></span>
+
+<span class="tag token"><span class="tag token"><span class="punctuation token">&lt;</span>script</span> <span class="attr-name token">async</span> <span class="attr-name token">src</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>js/script3.js<span class="punctuation token">"</span></span><span class="punctuation token">&gt;</span></span><span class="tag token"><span class="tag token"><span class="punctuation token">&lt;/</span>script</span><span class="punctuation token">&gt;</span></span></code></pre>
+
+<p>你不能將元素的順序視為腳本載入順序。 <code>jquery.js</code> 可能會在 <code>script2.js</code> 與 <code>script3.js</code> 的之前或之後載入,在這個情況下,在腳本中依賴 <code>jquery</code> 的函數將會發生錯誤,因為被執行到的時候 <code>jquery</code> 還沒被定義(載入且解析完畢)。</p>
+
+<p>當有許多非立即要使用的腳本,而你只希望它們能盡快被載入完畢,就應該使用 <code>async</code> 。例如:你有一些遊戲內容的檔案需要載入,它將在遊戲開始後被用到。但是現在你只是需要顯示遊戲介紹、一些選單以及遊戲大廳,不希望等到所有內容都下載完成之後才顯示。</p>
+
+<p>使用 <code>defer</code> 屬性(如下所示)所載入的腳本,會在腳本與內容都下載完成後,依照出現順序被執行。</p>
+
+<pre class="brush: html line-numbers language-html notranslate"><code class="language-html"><span class="tag token"><span class="tag token"><span class="punctuation token">&lt;</span>script</span> <span class="attr-name token">defer</span> <span class="attr-name token">src</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>js/vendor/jquery.js<span class="punctuation token">"</span></span><span class="punctuation token">&gt;</span></span><span class="tag token"><span class="tag token"><span class="punctuation token">&lt;/</span>script</span><span class="punctuation token">&gt;</span></span>
+
+<span class="tag token"><span class="tag token"><span class="punctuation token">&lt;</span>script</span> <span class="attr-name token">defer</span> <span class="attr-name token">src</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>js/script2.js<span class="punctuation token">"</span></span><span class="punctuation token">&gt;</span></span><span class="tag token"><span class="tag token"><span class="punctuation token">&lt;/</span>script</span><span class="punctuation token">&gt;</span></span>
+
+<span class="tag token"><span class="tag token"><span class="punctuation token">&lt;</span>script</span> <span class="attr-name token">defer</span> <span class="attr-name token">src</span><span class="attr-value token"><span class="punctuation token">=</span><span class="punctuation token">"</span>js/script3.js<span class="punctuation token">"</span></span><span class="punctuation token">&gt;</span></span><span class="tag token"><span class="tag token"><span class="punctuation token">&lt;/</span>script</span><span class="punctuation token">&gt;</span></span></code></pre>
+
+<p>全部具有 <code>defer</code> 屬性的腳本會依據出現的順序載入。因此在第二個範例中,我們可以肯定 <code>jquery.js</code> 會在 <code>script2.js</code> 與 <code>script3.js</code> 之前被載入, <code>script2.js</code> 會在 <code>script3.js</code> 之前載入。在網頁的所有內容被載入完成之前,它是不會被執行的。當你的程式依賴著某些元素存在時(如:要調整頁面上一到多個元素),這個屬性很有用。</p>
+
+<p>總結一下:</p>
+
+<ul>
+ <li><code>async</code> 和 <code>defer</code> 屬性都是用來告訴瀏覽器使用獨立線程(行程)來下載腳本,同一時間頁面的其它部分(如 DOM 元件之類)也在下載,因此頁面的載入不會因為腳本被影響。</li>
+ <li>如果你的腳本應該立即被執行,而且不依賴其它腳本先被載入,就用 <code>async</code> 。</li>
+ <li>如果你的腳本依賴其他腳本先被解析或 DOM 已經存在,就用 <code>defer</code> 來載入它們,並根據你想要瀏覽器執行的順序安排 <code>&lt;script&gt;</code> 元素的次序。</li>
+</ul>
+
+<h2 id="註解">註解</h2>
+
+<p>如同 HTML 和 CSS,在 JavaScript 的程式碼中也可以撰寫註解,它會被瀏覽器忽略,僅用來提供你的開發伙伴,說明程式是如何運作(或是自己,當六個月後回來看程式碼,忘記曾經做過了什麼)。註解非常有用,你應該常常使用它,尤其是在大型應用程式裡。註解有兩種形式:</p>
+
+<ul>
+ <li>單行註解,寫在兩個(正)斜線「//」之後,例如:
+ <pre class="brush: js notranslate">// 我是一個註解</pre>
+ </li>
+ <li>多行註解,寫在 /* 和 */ 之間的文字,例如:
+ <pre class="brush: js notranslate">/*
+ 我也是
+ 一個註解
+*/</pre>
+ </li>
+</ul>
+
+<p>舉例來說,我們可以在前面範例的 JavaScript 裡加入註解,像是:</p>
+
+<pre class="brush: js notranslate">// 函數:建立一個段落元素並加到 HTML body 的尾端
+
+function createParagraph() {
+ var para = document.createElement('p');
+ para.textContent = 'You clicked the button!';
+ document.body.appendChild(para);
+}
+
+/*
+ 1. 找出頁面上所有按鈕,並把它們放到陣列中
+ 2. 使用迴圈,對每個按鈕偵聽 click 事件
+
+ 當任何按鈕被按下,執行 createParagraph() 函數
+*/
+
+var buttons = document.querySelectorAll('button');
+
+for (var i = 0; i &lt; buttons.length ; i++) {
+ buttons[i].addEventListener('click', createParagraph);
+}</pre>
+
+<div class="blockIndicator note">
+<p><strong>注意:一般而言,多寫註解比少寫來得好。但是要注意,如果你發現加了許多註解在說明變數的用途(那麼你的變數命名可能需要更直觀,更帶有意義),或是解釋非常簡單的操作(也許你的程式碼太過於複雜)。</strong></p>
+</div>
+
+<h2 id="總結">總結</h2>
+
+<p>所以你已經踏出在 JavaScript 世界中的第一步。我們從理論開始,逐漸熟悉使用 JavaScript 的原因,以及你可以用它做些什麼。過程中你看到了一些程式碼範例,學到如何將 JavaScript 與你網站的其它東西放在一起。</p>
+
+<p>JavaScript 目前可能看起來有一點嚇人,然而不用擔心,在本課程我們會透過簡單的步驟,帶著你建立觀念並繼續向前。 在下一章節,我們將會<a href="/zh-TW/docs/Learn/JavaScript/Introduction_to_JavaScript_1/A_first_splash">投入更實用的知識</a>,帶你直接入門並建立你自己的 JavaScript 作品。</p>
+
+<h2 id="在這個學習模組中">在這個學習模組中</h2>
+
+<ul>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_is_JavaScript">什麼是JavaScript?</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/A_first_splash">初次接觸Javascript</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_went_wrong">什麼出錯了? JavaScript 的疑難排解(除錯)</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Variables">儲存你需要的資訊 — 變數</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Math">JavaScript 的基本運算— 數字 與 運算子</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Strings">處理文字 — JavaScript 的字串</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Useful_string_methods">有用的字串方法</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Arrays">陣列</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Silly_story_generator">附錄:笑話產生器</a></li>
+</ul>
+
+<p>{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}</p>
diff --git a/files/zh-tw/learn/javascript/first_steps/what_went_wrong/index.html b/files/zh-tw/learn/javascript/first_steps/what_went_wrong/index.html
new file mode 100644
index 0000000000..5eec96717b
--- /dev/null
+++ b/files/zh-tw/learn/javascript/first_steps/what_went_wrong/index.html
@@ -0,0 +1,253 @@
+---
+title: 出了什麼問題?JavaScript 疑難排解
+slug: Learn/JavaScript/First_steps/What_went_wrong
+translation_of: Learn/JavaScript/First_steps/What_went_wrong
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}</div>
+
+<p class="summary">當你在練習撰寫上一節的"猜數字"遊戲時,你可能會發現它無法運作。不用擔心,本文將會把你從快被拔光的頭髮中拯救出來,並且給你一些小提示,讓你知道怎麼找出及修正 Javascript 的程式運行錯誤。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">先備:</th>
+ <td>基本電腦能力,基本html及css理解以及了解JavaScript是什麼</td>
+ </tr>
+ <tr>
+ <th scope="row">目標:</th>
+ <td>獲得開始解決簡單編碼問題的能力及信心</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="錯誤類型">錯誤類型</h2>
+
+<p>一般來說,當你的編碼有錯誤時,主要有兩種類型</p>
+
+<ul>
+ <li><strong>語法錯誤</strong>: 在編碼中有一些拼字錯誤導致程序完全或部分沒有正常運作。在這個狀況下,通常你會獲得一些錯誤訊息。只要對工具熟悉以及了解錯誤訊息的意思,這種錯誤通常很好修正!</li>
+ <li><strong>邏輯錯誤</strong>: 這種錯誤代表程式碼的語法正確,但程式完成的部分不是開發者想做的?,意即程式碼執行成功,但返回錯誤的結果。這種錯誤通常比<strong>語法錯誤</strong>還要難修正,因為並沒有錯誤訊息讓我們可以很直接地知道程式碼的問題。</li>
+</ul>
+
+<p>好的,但事情並沒有那麼單純——當你越深入,就會發現更多不同的因素。但上述的分類已經足夠應付初期的工程師職涯了。接著,我們將更深入來討論這兩個類型。</p>
+
+<h2 id="一個錯誤範例">一個錯誤範例</h2>
+
+<p>讓我們從剛剛的猜數字遊戲開始 — 在這個版本中,我們將故意引入一些錯誤以便從中學習。前往 Github 下載一份 <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/troubleshooting/number-game-errors.html">number-game-errors.html</a> (或運行線上版 <a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/troubleshooting/number-game-errors.html">running live here</a>).</p>
+
+<ol>
+ <li>首先,在編輯器與瀏覽器分別開啟你剛下載檔案。</li>
+ <li>試著玩遊戲——你會注意到當你按下按鈕「Submit guess」時,它沒有任何反應!</li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: 你也許是想修復你自己寫的遊戲中的錯誤!這是件好事,但我們還是建議你在學習這篇文章時先使用我們的版本,這樣你才可以學到我們接下來要教的技巧。在這之後再回去修正你自己的遊戲也不遲!</p>
+</div>
+
+<p>現在,先讓我們來看看開發者主控台有沒有提示我們任何錯誤,然後試著修正他們。你會在接下來的段落中學到如何修正這些錯誤。</p>
+
+<h2 id="修復語法錯誤">修復語法錯誤</h2>
+
+<p>在前篇文章中我們讓你在 <a href="/zh-TW/docs/Learn/Common_questions/What_are_browser_developer_tools" rel="nofollow">開發者工具 JavaScript console</a> 中輸入了一些JavaScript 指令(如果你不記得怎麼打開這個東西,點選前面的連結複習一下)。更重要的是,主控台在瀏覽器的 JavaScript引擎讀取到有語法錯誤的 JavaScript 時會提示一些錯誤訊息。現在讓我們來看看:</p>
+
+<ol>
+ <li>切換到你開啟了 <code>number-game-errors.html</code> 的分頁,然後打開你的 JavaScript 主控台。你應該會看到如下的幾行錯誤訊息:<img alt="" src="https://mdn.mozillademos.org/files/13496/not-a-function.png" style="display: block; margin: 0 auto;"></li>
+ <li>這是一個非常容易追尋的錯誤,而且瀏覽器還給你了不少有用的資訊來幫助你(這張截圖是 Firefox 的,但其他瀏覽器也會提示相似的錯誤訊息)。從左到右,我們可以看到:
+ <ul>
+ <li>一個紅色的 "X" 代表這是一個錯誤訊息。</li>
+ <li>一條錯誤訊息提示你什麼東西出錯了:"TypeError: guessSubmit.addeventListener is not a function(TypeError: guessSubmit.addeventListener 並不是一個函式)"</li>
+ <li>一個 "Learn More" 連結連向一個解釋這個錯誤並包含大量詳細資訊的 MDN 頁面。</li>
+ <li>出錯的 JavaScript 檔案名稱,連結連向開發者工具的除錯器。點下這個連結,你就能看到出錯的那行程式被高亮顯示出來。</li>
+ <li>在該 JavaScript 檔案中錯誤的行號,還有錯誤發生在該行第幾個字元。在這個例子中,是第 86 行的第 3 個字元。</li>
+ </ul>
+ </li>
+ <li>如果我們在編輯器中檢視第 86 行,我們會看到:
+ <pre class="brush: js notranslate">guessSubmit.addeventListener('click', checkGuess);</pre>
+ </li>
+ <li>主控台提示的錯誤訊息寫著 "guessSubmit.addeventListener is not a function(guessSubmit.addeventListener 並不是一個函式)",所以我們大概是哪裡拼錯字了。如果你並不確定一個函式的正確名稱如何拼寫,打開 MDN 確認看看是個不錯的選擇。最佳做法是在你喜歡的搜尋引擎搜尋 "mdn <em>關鍵字</em>"。為了節省時間,這裡提供你一個捷徑:<code><a href="/zh-TW/docs/Web/API/EventTarget/addEventListener">addEventListener()</a></code>。</li>
+ <li>回來看看這個頁面,我們明顯是把函式名稱給拼錯了!記住,JavaScript 是會區分大小寫的,所以任何些微的拼寫錯誤甚至是大小寫錯誤都會造成錯誤發生。把<code>addeventListener</code> 改成<code>addEventListener</code> 問題就解決了。現在將你的程式碼修正吧。</li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: 看看這個 <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function">TypeError: "x" is not a function</a> 連結來了解更多有關這類錯誤的資訊。</p>
+</div>
+
+<h3 id="語法錯誤:第二回合">語法錯誤:第二回合</h3>
+
+<ol>
+ <li>將你的頁面存檔並重整,你現在應該會看到剛剛的錯誤消失了。</li>
+ <li>現在試著輸入一個猜測並按下 Submit guess 按鈕,你會發現... 另一個錯誤!<img alt="" src="https://mdn.mozillademos.org/files/13498/variable-is-null.png" style="display: block; margin: 0 auto;"></li>
+ <li>這次的錯誤是 "TypeError: lowOrHi is null(TypeError: lowOrHi 為 null)",在第 78 行的位置。
+ <div class="note"><strong>Note</strong>: <code><a href="/zh-TW/docs/Glossary/Null">Null</a></code> 是一個特別的值,代表著「空」、「什麼都沒有」。<code>lowOrHi</code> 被宣告為一個變數,但並沒有被賦予任何有意義的值 — 他既沒有變數型態,也沒有值。</div>
+
+ <div class="note"><strong>Note</strong>: 這個錯誤並沒有在頁面載入完成後就發生,因為這個錯誤發生在一個函式中(在 <code>checkGuess() { ... }</code> 區塊中)。在之後詳細介紹函式的文章中,你會學到在函式中的程式碼與在函式外的程式碼其實是執行在不同範疇中的。在我們的這個情況裡,有錯誤的程式碼在 <code>checkGuess()</code> 在 86 行被執行前都並沒有執行,也因此錯誤並沒有在頁面一載入就發生。</div>
+ </li>
+ <li>看看第 78 行,你會看到:
+ <pre class="brush: js notranslate">lowOrHi.textContent = 'Last guess was too high!';</pre>
+ </li>
+ <li>這行試著將 <code>lowOrHi</code> 的 <code>textContent</code> 屬性設為一個字串。但是這行沒有執行成功,因為 <code>lowOrHi</code> 並沒有存著它應該要存著的值。讓我們來看看為什麼 — 試試在程式碼中搜尋其他 <code>lowOrHi</code> 有出現的地方。在第 48 行你會看到:
+ <pre class="brush: js notranslate">var lowOrHi = document.querySelector('lowOrHi');</pre>
+ </li>
+ <li>這行程式碼試著將一個 HTML 元素的參照存起來。讓我們檢查一下在這行程式碼執行後,變數中的值是否為 <code>null</code>。在第 49 行加上:
+ <pre class="brush: js notranslate">console.log(lowOrHi);</pre>
+
+ <div class="note">
+ <p><strong>Note</strong>: <code><a href="/zh-TW/docs/Web/API/Console/log">console.log()</a></code> 是一個非常好用的除錯功能,它能夠將值印出至主控台中。所以這行程式碼會在第 48 行賦值給 <code>lowOrHi</code> 後,將它的值印出至主控台中。</p>
+ </div>
+ </li>
+ <li>存檔並重整,你應該會在主控台中看到 <code>console.log()</code> 輸出的結果。<img alt="" src="https://mdn.mozillademos.org/files/13494/console-log-output.png" style="display: block; margin: 0 auto;">在這個時間點,<code>lowOrHi</code> 的值是 <code>null</code>。所以很明顯的,第 48 行一定出了什麼問題。</li>
+ <li>讓我們思考一下發生了什麼問題。第 48 行呼叫了 <code><a href="/zh-TW/docs/Web/API/Document/querySelector">document.querySelector()</a></code> 方法來透過 CSS 選擇器取得一個 HTML 元素參照。打開我們的網頁看看我們想要取得的段落元素:
+ <pre class="brush: js notranslate">&lt;p class="lowOrHi"&gt;&lt;/p&gt;</pre>
+ </li>
+ <li>所以我們需要的是一個開頭是小數點 (.) 的 class 選擇器,但傳進第48 行 <code>querySelector()</code> 方法的選擇器並沒有開頭的小數點。這也許就是問題所在了!試著將第 48 行的 <code>lowOrHi</code> 改成 <code>.lowOrHi</code>。</li>
+ <li>再次存檔並重整,你的 <code>console.log()</code> 現在應該會輸出我們想要的 <code>&lt;p&gt;</code> 元素了。呼!又修好了另一個錯誤!你現在可以把你的 <code>console.log()</code> 那行移除了,或是你想要留著之後查看 — 取決於你。</li>
+</ol>
+
+<div class="note">
+<p><strong>Note</strong>: 看看這個 <a href="/zh-TW/docs/Web/JavaScript/Reference/Errors/Unexpected_type">TypeError: "x" is (not) "y"</a> 連結來了解更多有關這類錯誤的資訊。</p>
+</div>
+
+<h3 id="語法錯誤:第三回合">語法錯誤:第三回合</h3>
+
+<ol>
+ <li>現在如果你試著再次玩這個遊戲應該會相當順利,直到該讓遊戲結束的時機點才會發生錯誤:無論是猜對還是10次用完。</li>
+ <li>此時console提供錯誤訊息跟一開始一樣: "TypeError: resetButton.addeventListener is not a function"! 然而此次錯誤來自第94行。查看第94行後,我們可以輕易發現依舊是屬性大小寫問題,一樣把<code>addeventListener</code> 改成 <code>.addEventListener</code>就沒問題了。</li>
+</ol>
+
+<h2 id="邏輯錯誤">邏輯錯誤</h2>
+
+<p>到這邊為止遊戲應該可以進行得很順利,然而玩幾次下來無疑地你會發現「隨機」數字總是0或1,這可不是我們想要的!</p>
+
+<ol>
+ <li>搜尋位於44行的變數<code>randomNumber</code>,其內容是設定遊戲一開始的隨機數字:
+
+ <pre class="brush: js notranslate">var randomNumber = Math.floor(Math.random()) + 1;</pre>
+ </li>
+ <li>另一個開始新回合時產生隨機數字的變數則在113行左右:
+ <pre class="brush: js notranslate">randomNumber = Math.floor(Math.random()) + 1;</pre>
+ </li>
+ <li>為了測試問題是否出在這兩段程式碼,我們需要再次邀請<code>console.log()</code> 好朋友,將之分別放到44、113行的程式碼下一行:
+ <pre class="brush: js notranslate">console.log(randomNumber);</pre>
+ </li>
+ <li>儲存程式碼並更新頁面,然後再試玩幾次,你會看到<code>randomNumber</code> 在console中總是等於1,這就是問題所在。</li>
+</ol>
+
+<h3 id="修正小錯誤">修正小錯誤</h3>
+
+<p>為了修正這個錯誤,我們得先了解它是怎麼運作的。首先,我們呼叫<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random">Math.random()</a></code>以產生一個介於0到1的隨機小數,例如: 0.5675493843</p>
+
+<pre class="brush: js notranslate">Math.random()</pre>
+
+<p>接著,我們將<code>Math.random()</code> 產生的隨機小數傳進<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor">Math.floor()</a></code>,函式會回傳小於等於所給數字的最大整數,然後為這個整數值加1:</p>
+
+<pre class="notranslate">Math.floor(Math.random()) + 1</pre>
+
+<p><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">由於</span></font><code>Math.floor</code>是無條件捨去取整數(地板值),所以一個介於0到1的隨機小數永遠只會得到0,幫這個小數加1的話又會永遠只得到1。所以進位前我們先幫隨機小數乘上100 ,如此一來我們就能得到介於0到99的隨機數字了:</p>
+
+<pre class="brush: js notranslate">Math.floor(Math.random()*100);</pre>
+
+<p>別忘了還要加上1,數字範圍才能成功介於1到100:</p>
+
+<pre class="brush: js notranslate">Math.floor(Math.random()*100) + 1;</pre>
+
+<p>試著自己動手更新這兩行程式碼吧,儲存並更新頁面後你應該能看到遊戲如預期般進行!</p>
+
+<h2 id="其他常見錯誤">其他常見錯誤</h2>
+
+<p>還有些初學者非常容易忽略的小問題,這小節讓我們來概覽一下:</p>
+
+<h3 id="語法錯誤:語句缺少「_」_(SyntaxError_missing_before_statement)">語法錯誤:語句缺少「 ; 」<br>
+ (SyntaxError: missing ; before statement)</h3>
+
+<p>這個錯誤是指每行程式碼結束時必須加上英文輸入法的分號<code>;</code>(請注意不要打成中文輸入法),分號被遺忘的錯誤有時不太容易發現,此外另舉一例:如果我們改動下方變數<code>checkGuess()</code> 中的程式碼:</p>
+
+<pre class="brush: js notranslate">var userGuess = Number(guessField.value);</pre>
+
+<p>改成</p>
+
+<pre class="brush: js notranslate">var userGuess === Number(guessField.value);</pre>
+
+<p>此時程式碼會回報錯誤,因為瀏覽器會認為你想設定不同的東西;我們需要確保自己沒有誤用、混用指派運算子(<code>=</code>):用於賦予變數值跟嚴格比較運算子(<code>===</code>):用於比較兩個值是否完全相等,並回覆<code>true</code>/<code>false</code>布林值。</p>
+
+<div class="note">
+<p><strong>Note</strong>: 更多細節請參考右方關於<em>缺少分號的語法錯誤</em>文章頁面: <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement">SyntaxError: missing ; before statement</a> 。</p>
+</div>
+
+<h3 id="無論輸入什麼,程序總是顯示「你贏了」">無論輸入什麼,程序總是顯示「你贏了」</h3>
+
+<p>還有另一種混用指派運算子(<code>=</code>)與嚴格比較運算子(<code>===</code>)的狀況,舉例如果我們將變數 <code>checkGuess()</code>中的嚴格比較運算子(<code>===</code>)</p>
+
+<pre class="brush: js notranslate">if (userGuess === randomNumber) {</pre>
+
+<p>改成指派運算子(<code>=</code>)</p>
+
+<pre class="brush: js notranslate">if (userGuess = randomNumber) {</pre>
+
+<p>這個檢查就失效了,程式會永遠回傳 <code>true</code>而勝利並結束遊戲。請小心!</p>
+
+<h3 id="語法錯誤:參數列表後面缺少「」_(SyntaxError_missing_after_argument_list)">語法錯誤:參數列表後面缺少「)」 <br>
+ (SyntaxError: missing ) after argument list)</h3>
+
+<p>給完函數或方法參數時別忘了放上<code>)</code>右括號(請注意不要打成中文輸入法)。</p>
+
+<div class="note">
+<p><strong>Note</strong>: 更多細節請參考右方關於<em>缺少右括號的語法錯誤</em>文章頁面:<a href="/en-US/docs/Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list">SyntaxError: missing ) after argument list</a> 。</p>
+</div>
+
+<h3 id="語法錯誤:屬性ID後缺少「」_SyntaxError_missing_after_property_id">語法錯誤:屬性ID後缺少「:」<br>
+ SyntaxError: missing : after property id</h3>
+
+<p>This error usually relates to an incorrectly formed JavaScript object, but in this case we managed to get it by changing</p>
+
+<pre class="brush: js notranslate">function checkGuess() {</pre>
+
+<p>to</p>
+
+<pre class="brush: js notranslate">function checkGuess( {</pre>
+
+<p>This has caused the browser to think that we are trying to pass the contents of the function into the function as an argument. Be careful with those parentheses!</p>
+
+<h3 id="語法錯誤:「」缺少SyntaxError_missing_after_function_body">語法錯誤:「}」缺少SyntaxError: missing } after function body</h3>
+
+<p>This is easy — it generally means that you've missed one of your curly braces from a function or conditional structure. We got this error by deleting one of the closing curly braces near the bottom of the <code>checkGuess()</code> function.</p>
+
+<h3 id="SyntaxError_expected_expression_got_string_or_SyntaxError_unterminated_string_literal">SyntaxError: expected expression, got '<em>string</em>' or SyntaxError: unterminated string literal</h3>
+
+<p>These errors generally mean that you've missed off a string value's opening or closing quote mark. In the first error above, <em>string</em> would be replaced with the unexpected character(s) that the browser found instead of a quote mark at the start of a string. The second error means that the string has not been ended with a quote mark.</p>
+
+<p>For all of these errors, think about how we tackled the examples we looked at in the walkthrough. When an error arises, look at the line number you are given, go to that line and see if you can spot what's wrong. Bear in mind that the error is not necessarily going to be on that line, and also that the error might not be caused by the exact same problem we cited above!</p>
+
+<div class="note">
+<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Unexpected_token">SyntaxError: Unexpected token</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Unterminated_string_literal">SyntaxError: unterminated string literal</a> reference pages for more details about these errors.</p>
+</div>
+
+<h2 id="小結">小結</h2>
+
+<p>So there we have it, the basics of figuring out errors in simple JavaScript programs. It won't always be that simple to work out what's wrong in your code, but at least this will save you a few hours of sleep and allow you to progress a bit faster when things don't turn out right earlier on in your learning journey.</p>
+
+<h2 id="See_also">See also</h2>
+
+<div>
+<ul>
+ <li>There are many other types of errors that aren't listed here; we are compiling a reference that explains what they mean in detail — see the <a href="/en-US/docs/Web/JavaScript/Reference/Errors">JavaScript error reference</a>.</li>
+ <li>If you come across any errors in your code that you aren't sure how to fix after reading this article, you can get help! Ask on the <a class="external external-icon" href="https://discourse.mozilla-community.org/t/learning-web-development-marking-guides-and-questions/16294">Learning Area Discourse thread</a>, or in the <a href="irc://irc.mozilla.org/mdn">#mdn</a> IRC channel on <a class="external external-icon" href="https://wiki.mozilla.org/IRC">Mozilla IRC</a>. Tell us what your error is, and we'll try to help you. A listing of your code would be useful as well.</li>
+</ul>
+</div>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}</p>
+
+<h2 id="在這個學習模組中">在這個學習模組中</h2>
+
+<ul>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_is_JavaScript">什麼是JavaScript?</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/A_first_splash">初次接觸Javascript</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_went_wrong">什麼出錯了? JavaScript 的疑難排解(除錯)</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Variables">儲存你需要的資訊 — 變數</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Math">JavaScript 的基本運算— 數字 與 運算子</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Strings">處理文字 — JavaScript 的字串</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Useful_string_methods">有用的字串方法</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Arrays">陣列</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Silly_story_generator">附錄:笑話產生器</a></li>
+</ul>
diff --git a/files/zh-tw/learn/javascript/howto/index.html b/files/zh-tw/learn/javascript/howto/index.html
new file mode 100644
index 0000000000..5e5f7257c2
--- /dev/null
+++ b/files/zh-tw/learn/javascript/howto/index.html
@@ -0,0 +1,294 @@
+---
+title: JavaScript 解決常見的問題
+slug: Learn/JavaScript/Howto
+translation_of: Learn/JavaScript/Howto
+---
+<div>{{LearnSidebar}}<br>
+以下鏈接針對您需要修復的常見問題的解決方案,以便讓您的JavaScript語法正確執行。</div>
+
+<h2 id="初學者常見的錯誤"><strong>初學者常見的錯誤</strong></h2>
+
+<h3 id="糾正語法和代碼">糾正語法和代碼</h3>
+
+<p><br>
+  </p>
+
+<p>如果您的代碼毫無反映或瀏覽器反饋某些內容「未定義」,請檢查您是否「正確輸入」所有變量名稱,函數名稱等。</p>
+
+<p>以下的常見造成問題的內置瀏覽器功能比對:</p>
+
+<p> </p>
+
+<table class="standard-table">
+ <thead>
+ <tr>
+ <th scope="col"><strong>正確</strong></th>
+ <th scope="col"><strong><span style="display: none;"> </span>錯誤<span style="display: none;"> </span></strong></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>getElementsByTagName()</code></td>
+ <td><code>getElementbyTagName()</code></td>
+ </tr>
+ <tr>
+ <td><code>getElementsByName()</code></td>
+ <td><code>getElementByName()</code></td>
+ </tr>
+ <tr>
+ <td><code>getElementsByClassName()</code></td>
+ <td><code>getElementByClassName()</code></td>
+ </tr>
+ <tr>
+ <td><code>getElementById()</code></td>
+ <td><code>getElementsById()</code></td>
+ </tr>
+ </tbody>
+</table>
+
+<h3 id="分號位置">分號位置</h3>
+
+<p>You need to make sure you don't place any semi-colons incorrectly. For example:</p>
+
+<table class="standard-table">
+ <thead>
+ <tr>
+ <th scope="col">Correct</th>
+ <th scope="col">Wrong</th>
+ </tr>
+ <tr>
+ <td><code>elem.style.color = 'red';</code></td>
+ <td><code>elem.style.color = 'red;'</code></td>
+ </tr>
+ </thead>
+</table>
+
+<h3 id="功能內容">功能內容</h3>
+
+<p>There are a number of things that can go wrong with functions.</p>
+
+<p>One of the most common errors is to declare the function, but not call it anywhere. For example:</p>
+
+<pre class="brush: js">function myFunction() {
+ alert('This is my function.');
+};</pre>
+
+<p>This code won't do anything unless you call it, for example with</p>
+
+<pre class="brush: js">myFunction();</pre>
+
+<h4 id="功能範圍"><strong>功能範圍</strong></h4>
+
+<p>Remember that <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Function_scope_and_conflicts">functions have their own scope</a> — you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e. not inside any functions), or <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Return_values">return the value</a> out of the function.</p>
+
+<h4 id="在return語句後執行語法">在return語句後執行語法</h4>
+
+<p>Remember also that when you return a value out of a function, the JavaScript interpreter exits the function — no code declared after the return statement will run.</p>
+
+<p>In fact, some browsers (like Firefox) will give you an error message in the developer console if you have code after a return statement. Firefox gives you "unreachable code after return statement".</p>
+
+<h3 id="對象表示法與正確的指派">對象表示法與正確的指派</h3>
+
+<p>When you assign something normally in JavaScript, you use a single equals sign, e.g.:</p>
+
+<pre class="brush: js">const myNumber = 0;</pre>
+
+<p>This doesn't work in <a href="/en-US/docs/Learn/JavaScript/Objects">Objects</a>, however — with objects you need to separate member names from their values using colons, and separate each member with a comma, for example:</p>
+
+<pre class="brush: js">const myObject = {
+ name: 'Chris',
+ age: 38
+}</pre>
+
+<h2 id="基本定義"><strong>基本定義</strong></h2>
+
+<div class="column-container">
+<div class="column-half">
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript#A_high-level_definition">What is JavaScript?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables#What_is_a_variable">What is a variable?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">What are strings?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays#What_is_an_Array">What is an array?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code">What is a loop?</a></li>
+</ul>
+</div>
+
+<div class="column-half">
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">What is a function?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events">What is an event?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics#Object_basics">What is an object?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/JSON#No_really_what_is_JSON">What is JSON?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction#What_are_APIs">What is a web API?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents#The_document_object_model">What is the DOM?</a></li>
+</ul>
+</div>
+</div>
+
+<h2 id="基本使用例子">基本使用例子</h2>
+
+<div class="column-container">
+<div class="column-half">
+<h3 id="概括">概括</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript#How_do_you_add_JavaScript_to_your_page">How do you add JavaScript to your page?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript#Comments">How do you add comments to JavaScript code?</a></li>
+</ul>
+
+<h3 id="變量">變量</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables#Declaring_a_variable">How do you declare a variable?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables#Initializing_a_variable">How do you initialize a variable with a value?</a></li>
+ <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables#Updating_a_variable">How do you update a variable's value?</a> (also see <a href="/en-US/docs/Learn/JavaScript/First_steps/Math#Assignment_operators">Assignment operators</a>)</li>
+ <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables#Variable_types">What data types can values have in JavaScript?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables#Loose_typing">What does 'loosely typed' mean?</a></li>
+</ul>
+
+<h3 id="數學運算">數學運算</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math#Types_of_numbers">What types of number do you have to deal with in web development?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math#Arithmetic_operators">How do you do basic math in JavaScript?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math#Operator_precedence">What is operator precedence, and how is it handled in JavaScript?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math#Increment_and_decrement_operators">How do you increment and decrement values in JavaScript?</a></li>
+ <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Math#Comparison_operators">How do you compare values in JavaScript?</a> (e.g. to see which one is bigger, or to see if one value is equal to another).</li>
+</ul>
+
+<h3 id="字串">字串</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings#Creating_a_string">How do you create a string in JavaScript?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings#Single_quotes_versus_double_quotes">Do you have to use single quotes or double quotes?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings#Escaping_characters_in_a_string">How do you escape characters in strings?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings#Concatenating_strings">How do you join strings together?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings#Numbers_versus_strings">Can you join strings and numbers together?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#Finding_the_length_of_a_string">How do you find the length of a string?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#Retrieving_a_specific_string_character">How you find what character is at a certain position in a string?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#Finding_a_substring_inside_a_string_and_extracting_it">How do you find and extract a specific substring from a string?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#Changing_case">How do you change the case of a string?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#Updating_parts_of_a_string">How do you replace one specific substring with another?</a></li>
+</ul>
+</div>
+
+<div class="column-half">
+<h3 id="序列">序列</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays#Creating_an_array">How do you create an array?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays#Accessing_and_modifying_array_items">How do you access and modify the items in an array?</a> (this includes multidimensional arrays)</li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays#Finding_the_length_of_an_array">How do you find the length of an array?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays#Adding_and_removing_array_items">How you add and remove array items?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays#Converting_between_strings_and_arrays">How do you split a string into array items, or join array items into a string?</a></li>
+</ul>
+
+<h3 id="Debugging_JavaScript">Debugging JavaScript</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong#Types_of_error">What are the basic types of error?</a></li>
+ <li><a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">What are browser developer tools, and how do you access them?</a></li>
+ <li><a href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript#The_Console_API">How do you log a value to the JavaScript console?</a></li>
+ <li><a href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript#Using_the_JavaScript_debugger">How do you use breakpoints, and other JavaScript debugging features?</a></li>
+</ul>
+
+<p>For more information on JavaScript debugging, see <a href="/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript">Handling common JavaScript problems</a>; also see <a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong#Other_common_errors">Other common errors</a> for a description of common errors.</p>
+
+<h3 id="Making_decisions_in_code">Making decisions in code</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals">How do you execute different blocks of code, depending on a variable's value or other condition?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#if_..._else_statements">How do you use if ...else statements?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#Nesting_if_..._else">How do nest one decision block inside another?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#Logical_operators_AND_OR_and_NOT">How do you use AND, OR, and NOT operators in JavaScript?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#switch_statements">How do you conveniently handle a large number of choices for one condition?</a></li>
+ <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals#Ternary_operator">How do you use a ternary operator to make a quick choice between two options based on a true or false test?</a></li>
+</ul>
+
+<h3 id="Loopingiteration">Looping/iteration</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code">How do you run the same bit of code over and over again?</a></li>
+ <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#Exiting_loops_with_break">How do you exit a loop before the end if a certain condition is met?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#Skipping_iterations_with_continue">How do you skip to the next iteration of a loop if a certain condition is met?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#while_and_do_..._while">How do you use while and do ... while loops?</a></li>
+ <li>How to iterate over the elements in an array</li>
+ <li>How to iterate over the elements in a multidimensional array</li>
+ <li>How to iterate over the members in an object</li>
+ <li>How to iterate over the members of an object nested inside an array</li>
+</ul>
+</div>
+</div>
+
+<h2 id="進階使用例子">進階使用例子</h2>
+
+<div class="column-container">
+<div class="column-half">
+<h3 id="Functions">Functions</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Built-in_browser_functions">How do you find functions in the browser?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Functions_versus_methods">What is the difference between a function and a method?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Build_your_own_function">How do you create your own functions?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Invoking_functions">How do you run (call, or invoke) a function?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Anonymous_functions">What is an anonymous function?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Function_parameters">How do you specify parameters (or arguments) when invoking a function?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions#Function_scope_and_conflicts">What is function scope?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Return_values">What are return values, and how do you use them?</a></li>
+</ul>
+
+<h3 id="對向">對向</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics#Object_basics">How do you create an object?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics#Dot_notation">What is dot notation?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation">What is bracket notation?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics#Setting_object_members">How do you get and set the methods and properties of an object?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics#What_is_this">What is <code>this</code>, in the context of an object?</a></li>
+ <li><a href="/docs/Learn/JavaScript/Objects/Object-oriented_JS#Object-oriented_programming_from_10000_meters">What is object-oriented programming?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS#Constructors_and_object_instances">What are constructors and instances, and how do you create them?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS#Other_ways_to_create_object_instances">What different ways are there to create objects in JavaScript?</a></li>
+</ul>
+
+<h3 id="JSON">JSON</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/JSON#JSON_structure">How do you structure JSON data, and read it from JavaScript?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/JSON#Loading_our_JSON">How can you load a JSON file into a page?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/JSON#Converting_between_objects_and_text">How do you convert a JSON object to a text string, and back again?</a></li>
+</ul>
+</div>
+
+<div class="column-half">
+<h3 id="任務">任務</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_handler_properties">What are event handlers and how do you use them?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_%E2%80%94_don%27t_use_these">What are inline event handlers?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#addEventListener()_and_removeEventListener()">What does the <code>addEventListener()</code> function do, and how do you use it?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#What_mechanism_should_I_use">Which mechanism should I use to add event code to my web pages?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_objects">What are event objects, and how do you use them?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#Preventing_default_behaviour">How do you prevent default event behaviour?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture">How do events fire on nested elements? (event propagation, also related — event bubbling and capturing)</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation">What is event delegation, and how does it work?</a></li>
+</ul>
+
+<h3 id="Object-oriented_JavaScript">Object-oriented JavaScript</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">What are object prototypes?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object_prototypes#The_constructor_property">What is the constructor property, and how can you use it?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object_prototypes#Modifying_prototypes">How do you add methods to the constructor?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Inheritance">How do you create a new constructor that inherits its members from a parent constructor?</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Inheritance#Object_member_summary">When should you use inheritance in JavaScript?</a></li>
+</ul>
+
+<h3 id="網頁Web_APIs">網頁Web APIs</h3>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents#Active_learning_Basic_DOM_manipulation">How do you manipulate the DOM (e.g. adding or removing elements) using JavaScript?</a></li>
+</ul>
+
+<p> </p>
+</div>
+</div>
diff --git a/files/zh-tw/learn/javascript/index.html b/files/zh-tw/learn/javascript/index.html
new file mode 100644
index 0000000000..17fed115be
--- /dev/null
+++ b/files/zh-tw/learn/javascript/index.html
@@ -0,0 +1,71 @@
+---
+title: JavaScript — 動態的客戶端指令
+slug: Learn/JavaScript
+tags:
+ - Beginner
+ - CodingScripting
+ - JavaScript
+ - Landing
+ - NeedsTranslation
+ - Topic
+ - TopicStub
+ - 初學者
+translation_of: Learn/JavaScript
+---
+<div>{{LearnSidebar}}</div>
+
+<p class="summary">{{Glossary("JavaScript")}} 程式語言可讓你在網頁上建構複雜的事物。當網頁不僅僅呆板呈現給你靜態的內容(像是即時的內容更新,互動式地圖、2D/3D 動畫、滑鼠操控影片播放…等等),你可以大膽猜測 JavaScript 已經參與其中。</p>
+
+<h2 id="學習途徑">學習途徑</h2>
+
+<p>JavaScript 相較於 <a href="/zh-TW/docs/Learn/HTML">HTML</a> 和 <a href="/zh-TW/docs/Learn/CSS">CSS</a> 這些技術可以說比較困難。開始嘗試學習 JavaScript 之前,強烈建議你起碼先熟悉上述兩項技術,或者了解其它的更好。可以透過以下單元開始:</p>
+
+<ul>
+ <li><a href="/zh-TW/docs/Learn/Getting_started_with_the_web">入門認識 Web</a></li>
+ <li><a href="/zh-TW/docs/Learn/HTML/Introduction_to_HTML">HTML 簡介</a>.</li>
+ <li><a href="/zh-TW/docs/Learn/CSS/Introduction_to_CSS">CSS 簡介</a>.</li>
+</ul>
+
+<p>若你之前有其他程式語言的撰寫經驗,也許會有幫助。</p>
+
+<p>當熟悉 JavaScript 的基本知識之後,你應該進入一些更進階的主題,像是:</p>
+
+<ul>
+ <li>深入 JavaScript,像是 <a href="/zh-TW/docs/Web/JavaScript/Guide">JavaScript 指南</a></li>
+ <li><a href="/zh-TW/docs/Web/API">Web <u>APIs</u></a></li>
+</ul>
+
+<h2 id="單元">單元</h2>
+
+<p>本主題涵蓋許多單元,建議你依下列順序閱讀。</p>
+
+<dl>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/First_steps">JavaScript 初探</a></dt>
+ <dd>在我們的第一個 JavaScript 單元,在帶你初次實際撰寫 JavaScript 程式之前,我們先回答幾個基本的問題,像是「什麼是 JavaScript?」、「它看起來是什麼樣子?」、「它能做些什麼?」。接著,我們深入地討論幾個 JavaScript 關鍵的組成元素,例如:變數、字串、數字、陣列。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/Building_blocks">JavaScript 構成元素</a></dt>
+ <dd>在這個單元,我們繼續含蓋 JavaScript 關鍵的基本元素,把焦點放在常見程式碼區塊的類型,像是條件陳述式、迴圈、函數以及事件。你已經在這個課程中看過這些東西,但只是匆匆一瞥,在這裡我們會明確地討論。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/Objects">JavaScript 物件介紹</a></dt>
+ <dd>在 JavaScript 程式語言,絕大部分的東西都是物件,從核心的 JavaScript 元素像是字串(string)和陣列(array)到基於 JavaScript 建構的瀏覽器 API 都是。你甚至可以建立自己的物件,將相關的變數與函數封裝成能有效率操作的集合體。如果你想更深入了解這門程式語言的知識,並撰寫出更有效率的程式碼,了解 JavaScript 物件導向的本質是重要的,因此我們準備這個單元來幫助你。這裡我們教詳細的物件理論與語法,看看要如何建自你自己的物件,以及說明什麼是 JSON 資料和怎麼使用它。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/Asynchronous">非同步的 JavaScript</a></dt>
+ <dd>這個單元我們來討論非同步的 JavaScript,它為什麼重要,以及它能如何有效處理像是由伺服器抓取資料這種阻塞性操作(它會造成網頁停頓)。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/Client-side_web_APIs">用戶端的 web API</a></dt>
+ <dd>當你走在用 JavaScript 撰寫用戶端程式,來建構網站或應用程式的路上,不利用 API 很難走很遠,介接在操控瀏覽器、作業系統的不同功能,或是接收來自其它網站、服務的資料。在這個單元中,我們將討索什麼是 API ,以及如何使用幾個在你開發過程中,十分頻繁被使用到的 API 。</dd>
+ <dt>
+ <h2 id="解決常見的_JavaScript_問題">解決常見的 JavaScript 問題</h2>
+
+ <p>在你寫網頁時,可參閱〈<a href="/zh-TW/docs/Learn/JavaScript/Howto">透過 JavaScript 解決常見的問題</a>〉內所提供的連結,解決許多常見問題。</p>
+ </dt>
+</dl>
+
+<h2 id="參考資源">參考資源</h2>
+
+<dl>
+ <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">JavaScript on MDN</a></dt>
+ <dd>MDN 上連結到各篇 JavaScript 核心文件的主要,在這裡你可以找到關於 JavaScript 程式語言各方面廣泛的參考文件,還有一些進階的指引幫助你成為熟練的 JavaScript 使用者。</dd>
+ <dt><a href="https://learnjavascript.online/">Learn JavaScript</a></dt>
+ <dd>對於想成為網站開發者一個很好的資源,以互動的方式學習 JavaScript ,包含短課程、互動測驗,自動評估狀況給予指引。前 40 堂課是免費,完整的課程可以在一次付費買下。</dd>
+ <dt><a href="https://exlskills.com/learn-en/courses/javascript-fundamentals-basics_javascript">JavaScript Fundamentals on EXLskills</a></dt>
+ <dd>在免費的 EXLskills 開源課程中,介紹給你所有開始建構 JavaScript 應用程式所需要的東西。</dd>
+ <dt><a href="https://www.youtube.com/user/codingmath">Coding math</a></dt>
+ <dd>一系列優質的教學影片,教你需要了解哪些數學知識,來讓你成為有效率的程式設計師。(作者:<a href="https://twitter.com/bit101">Keith Peters</a>)</dd>
+</dl>
diff --git a/files/zh-tw/learn/javascript/objects/adding_bouncing_balls_features/index.html b/files/zh-tw/learn/javascript/objects/adding_bouncing_balls_features/index.html
new file mode 100644
index 0000000000..33cb338c8d
--- /dev/null
+++ b/files/zh-tw/learn/javascript/objects/adding_bouncing_balls_features/index.html
@@ -0,0 +1,184 @@
+---
+title: 為彈跳彩球添增其他功能
+slug: Learn/JavaScript/Objects/Adding_bouncing_balls_features
+translation_of: Learn/JavaScript/Objects/Adding_bouncing_balls_features
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/Objects/Object_building_practice", "", "Learn/JavaScript/Objects")}}</div>
+
+<p class="summary">在本文中,你將繼續使用前一篇文章的彈跳彩球展示程式,另外加入幾項有趣的新功能。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">必備條件:</th>
+ <td>在開始本文所提的實作之前,應先看過先前的相關文章。</td>
+ </tr>
+ <tr>
+ <th scope="row">要點:</th>
+ <td>測試 JavaScript 物件與 OO 架構的完整性。</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="開始">開始</h2>
+
+<p>在開始之前,請先複製先前文章所提供的 <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/bouncing-balls/index-finished.html">index-finished.html</a>、<a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/bouncing-balls/style.css">style.css</a>、<a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/bouncing-balls/main-finished.js">main-finished.js</a> 等檔案,儲存於本端磁碟的新資料夾中。</p>
+
+<div class="note">
+<p><strong>注意:</strong>你也可透過如 <a class="external external-icon" href="http://jsbin.com/">JSBin</a> 或 <a class="external external-icon" href="https://thimble.mozilla.org/">Thimble</a> 等網站進行此一實作。你可將 HTML、CSS、JavaScript 貼入相關線上編輯器之一。如果你所用的線上編輯器並未提供獨立的 JavaScript/CSS 面板,則可將之放入 HTML 頁面內的行內 <code>&lt;script&gt;</code>/<code>&lt;style&gt;</code> 元素中。</p>
+</div>
+
+<h2 id="專案簡介">專案簡介</h2>
+
+<p>彈跳彩球很有趣,但接著我們要加入使用者可控制的「邪惡圈」,在碰到彩球之後隨即吃掉彩球,添加更多互動性。也希望透過邪惡圈與彩球所繼承的通用 <code>Shape()</code> 物件,測試你的物件技術。最後還要加上計分功能,顯示尚未吃掉的彩球數量。</p>
+
+<p>下方擷圖則讓你了解最終成品的樣子:</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13875/bouncing-evil-circle.png" style="display: block; margin: 0 auto;"></p>
+
+<ul>
+</ul>
+
+<p>可先參考<a href="http://mdn.github.io/learning-area/javascript/oojs/assessment/">完成範例</a>讓心裡有個底 (別偷看原始碼啊!)</p>
+
+<h2 id="須進行的步驟">須進行的步驟</h2>
+
+<p>下列段落將逐步說明。</p>
+
+<h3 id="建立新物件">建立新物件</h3>
+
+<p>首先將現有的 <code>Ball()</code> 建構子變更為 <code>Shape()</code> 建構子,以及新的 <code>Ball()</code> 建構子:</p>
+
+<ol>
+ <li><code>Shape()</code> 建構子對 <code>x</code>、<code>y</code>、<code>velX</code>、<code>velY</code> 屬性的定義方式,就如同 <code>Ball()</code> 建構子所用的方式。</li>
+ <li>另須定義新的 <code>exists</code> 屬性,用以追蹤球體是否存在於程式之中 (也就是尚未遭邪惡圈所吃掉)。此屬性必為布林值 (Boolean),初始值為 <code>true</code>。</li>
+ <li><code>Ball()</code> 建構子應從 <code>Shape()</code> 建構子繼承 <code>x</code>、<code>y</code>、<code>velX</code>、<code>velY</code>、<code>exists</code> 等屬性。另必須將這些屬性定義為參數以利呼叫之。</li>
+ <li>必須定義 <code>color</code> 與 <code>size</code> 屬性各 1 組,且由於兩者均來自於原始的 <code>Ball()</code> 建構子之中,所以剛開始的隨機值亦須相同。</li>
+ <li>記得應正確設定 <code>Ball()</code> 建構子的 <code>prototype</code> 與 <code>constructor</code>。</li>
+</ol>
+
+<p>彩球的 <code>draw()</code>、<code>update()</code>、<code>collisionDetect()</code> 函式定義,均與之前完全相同。</p>
+
+<p>到此為止可重新載入程式碼,搭配重新設計的物件也應該運作無誤。</p>
+
+<h3 id="定義_EvilCircle()">定義 EvilCircle()</h3>
+
+<p>再來見見這個壞蛋 — <code>EvilCircle()</code>!這個遊戲要加入 1 個會吃球的邪惡圈,而且要透過繼承自 <code>Shape()</code> 的建構子來定義這個邪惡圈。你可能也想添增另個讓第二個玩家控制的圈圈,或許多加幾個由電腦控制的邪惡圈。當然,光一個邪惡圈並無法統治世界,但可為此遊戲增添不少樂趣。</p>
+
+<p><code>EvilCircle()</code> 建構子應繼承 <code>Shape()</code> 的 <code>x、</code><code>y、</code><code>exists。</code></p>
+
+<p>亦可定義自有的屬性如下:</p>
+
+<ul>
+ <li><code>color</code> — <code>'white'</code></li>
+ <li><code>size</code> — <code>10</code></li>
+ <li><code>velX</code> — <code>20</code></li>
+ <li><code>velY</code> — <code>20</code></li>
+</ul>
+
+<p>再次提醒,請記得要將所繼承的屬性在建構子中定義為參數,並應正確設定 <code>prototype</code> 與 <code>constructor</code> 屬性。</p>
+
+<h3 id="定義_EvilCircle()_的函式">定義 EvilCircle() 的函式</h3>
+
+<p><code>EvilCircle()</code> 應具備 4 個函式,如下:</p>
+
+<h4 id="draw()"><code>draw()</code></h4>
+
+<p>此函式的功能與 <code>Ball()</code> 的 <code>draw()</code> 函式相同,就是在 canvas 上繪製物件實體;且運作的方式也類似,所以你可以複製 <code>Ball.prototype.draw</code> 定義來開始。接著要完成下列改變:</p>
+
+<ul>
+ <li>我們要空心的邪惡圈,但不只是單純實心黑線畫成的圓而已 (要有邊框)。只要將 <code><a href="/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle">fillStyle</a></code> 與 <code><a href="/en-US/docs/Web/API/CanvasRenderingContext2D/fill">fill()</a></code> 更新成 <code><a href="/en-US/docs/Web/API/CanvasRenderingContext2D/strokeStyle">strokeStyle</a></code> 與 <code><a href="/en-US/docs/Web/API/CanvasRenderingContext2D/stroke">stroke()</a></code> 即可辦到。</li>
+ <li>還可以讓邊框更粗一點,有助你更容易看到邪惡圈。只要在 <code><a href="/en-US/docs/Web/API/CanvasRenderingContext2D/beginPath">beginPath()</a></code> 呼叫之後的某個地方設定 <code><a href="/en-US/docs/Web/API/CanvasRenderingContext2D/lineWidth">lineWidth</a></code> 的值 (「3」就可以) 即可。</li>
+</ul>
+
+<h4 id="checkBounds()"><code>checkBounds()</code></h4>
+
+<p>此函式功能就與 <code>Ball()</code> 的 <code>update()</code> 函式第一部分相同,負責邪惡圈是否跳出螢幕邊界之外並適時阻止。同樣的,你還是可以複製 <code>Ball.prototype.update</code> 定義來用,但須更改下列:</p>
+
+<ul>
+ <li>Get rid of the last two lines — we don't want to automatically update the evil circle's position on every frame, because we will be moving it in some other way, as you'll see below.</li>
+ <li>Inside the <code>if()</code> statements, if the tests return true we don't want to update <code>velX</code>/<code>velY</code>; we want to instead change the value of <code>x</code>/<code>y</code> so the evil circle is bounced back onto the screen slightly. Adding or subtracting (as appropriate) the evil circle's <code>size</code> property would make sense.</li>
+</ul>
+
+<h4 id="setControls()"><code>setControls()</code></h4>
+
+<p>This method will add an <code>onkeydown</code> event listener to the <code>window</code> object so that when certain keyboard keys are pressed, we can move the evil circle around. The following code block should be put inside the method definition:</p>
+
+<pre class="brush: js">var _this = this;
+window.onkeydown = function(e) {
+ if(e.keyCode === 65) {
+ _this.x -= _this.velX;
+ } else if(e.keyCode === 68) {
+ _this.x += _this.velX;
+ } else if(e.keyCode === 87) {
+ _this.y -= _this.velY;
+ } else if(e.keyCode === 83) {
+ _this.y += _this.velY;
+ }
+ }</pre>
+
+<p>So when a key is pressed, the event object's <a href="/en-US/docs/Web/API/KeyboardEvent/keyCode">keyCode</a> property is consulted to see which key is pressed. If it is one of the four represented by the specified keycodes, then the evil circle will move left/right/up/down.</p>
+
+<ul>
+ <li>For a bonus point, let us know which keys the specified keycodes map to.</li>
+ <li>For another bonus point, can you tell us why we've had to set <code>var _this = this;</code> in the position it is in? It is something to do with function scope.</li>
+</ul>
+
+<h4 id="collisionDetect()"><code>collisionDetect()</code></h4>
+
+<p>This method will act in a very similar way to <code>Ball()</code>'s <code>collisionDetect()</code> method, so you can use a copy of that as the basis of this new method. But there are a couple of differences:</p>
+
+<ul>
+ <li>In the outer <code>if</code> statement, you no longer need to check whether the current ball in the iteration is the same as the ball that is doing the checking — because it is not longer a ball, it is the evil circle! Instead, you need to do a test to see if the ball being checked exists (with which property could you do this with?). If it doesn't exist, it has already been eaten by the evil circle, so there is no need to check it again.</li>
+ <li>In the inner <code>if</code> statement, you no longer want to make the objects change color when a collision is detected — instead, you want to set any balls that collide with the evil circle to not exist any more (again, how do you think you'd do that?).</li>
+</ul>
+
+<h3 id="Bringing_the_evil_circle_into_the_program">Bringing the evil circle into the program</h3>
+
+<p>Now we've defined the evil circle, we need to actually make it appear in our scene. To do this, you need to make some changes to the <code>loop()</code> function.</p>
+
+<ul>
+ <li>First of all, create a new evil circle object instance, then call its <code>setControls()</code> method. You only need to do these two things once, not on every iteration of the loop.</li>
+ <li>At the point where you loop through every ball and call the <code>draw()</code>, <code>update()</code>, and <code>collisionDetect()</code> functions for each one, make it so that these functions are only called if the current ball exists.</li>
+ <li>Call the evil ball instance's <code>draw()</code>, <code>checkBounds()</code>, and <code>collisionDetect()</code> methods on every iteration of the loop.</li>
+</ul>
+
+<h3 id="Implementing_the_score_counter">Implementing the score counter</h3>
+
+<p>To implement the score counter, follow the following steps:</p>
+
+<ol>
+ <li>In your HTML file, add a {{HTMLElement("p")}} element just below the {{HTMLElement("h1")}} element containing the text "Ball count: ".</li>
+ <li>In your CSS file, add the following rule at the bottom:
+ <pre class="brush: css">p {
+ position: absolute;
+ margin: 0;
+ top: 35px;
+ right: 5px;
+ color: #aaa;
+}</pre>
+ </li>
+ <li>In your JavaScript, make the following updates:
+ <ul>
+ <li>Create a variable that stores a reference to the paragraph.</li>
+ <li>Keep a count of the number of balls on screen in some way.</li>
+ <li>Increment the count and display the updated number of balls each time a ball is added to the scene.</li>
+ <li>Decrement the count and display the updated number of balls each time the evil circle eats a ball (causes it not to exist).</li>
+ </ul>
+ </li>
+</ol>
+
+<h2 id="Hints_and_tips">Hints and tips</h2>
+
+<ul>
+ <li>This assessment is quite challenging. Take each step slowly and carefully.</li>
+ <li>It might be an idea to keep a separate copy of the demo after you get each stage working, so you can refer back to it if you find yourself in trouble later on.</li>
+</ul>
+
+<h2 id="交作業">交作業</h2>
+
+<p>如果你是在某個課堂上操作這份作業,那麼請將成品交給您的老師 / 助教;如果您是自學者,在我們的<a href="https://discourse.mozilla-community.org/t/learning-web-development-marking-guides-and-questions/16294">專屬討論區</a>或 <a href="https://wiki.mozilla.org/IRC">Mozilla IRC </a>上的 <a href="irc://irc.mozilla.org/mdn">#mdn</a> 頻道都可以很輕鬆地找到人給予指教。記得先認真做一下習題,要怎麼收獲先那麼栽呀!</p>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/Objects/Object_building_practice", "", "Learn/JavaScript/Objects")}}</p>
diff --git a/files/zh-tw/learn/javascript/objects/basics/index.html b/files/zh-tw/learn/javascript/objects/basics/index.html
new file mode 100644
index 0000000000..3b70536656
--- /dev/null
+++ b/files/zh-tw/learn/javascript/objects/basics/index.html
@@ -0,0 +1,243 @@
+---
+title: JavaScript 物件基礎概念
+slug: Learn/JavaScript/Objects/Basics
+translation_of: Learn/JavaScript/Objects/Basics
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}</div>
+
+<p class="summary">第一篇談到 JavaScript 物件的文章中,我們了解到基本的 JavaScript 物件語法,複習了某些先前提過的 JavaScript 功能,也再次強調你現正使用中的許多功能其實就是物件。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">必要條件:</th>
+ <td>基本的電腦素養、對 HTML 與 CSS 已有初步認識、熟悉 JavaScript 基本概念 (參閱〈<a href="/zh-TW/docs/Learn/JavaScript/First_steps">First steps</a>〉與〈<a href="/zh-TW/docs/Learn/JavaScript/Building_blocks">Building blocks</a>〉)。</td>
+ </tr>
+ <tr>
+ <th scope="row">主旨:</th>
+ <td>了解「物件導向 (OO)」程式設計背後的基礎理論、其與 JavaScript (多屬於物件) 之間的關係、該如何使用 JavaScript 物件進行開發。</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="物件基礎概念">物件基礎概念</h2>
+
+<p>物件是一批相關的數據以及/或者功能(通常包含了幾個變數及函式 — 當它們包含在物件中時被稱做「屬性」(properties)或「函式」(methods)),讓我們用一個範例來看看物件的長相。</p>
+
+<p>在開始之前,請先複製一份 <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/introduction/oojs.html">oojs.html</a> 檔案到你自己的本端硬碟中。此檔案內容物不多,就 1 組 {{HTMLElement("script")}} 元素可寫入我們的原始碼;在繪製頁面時,1 組元素可輸入簡易指令;幾個變數定義;1 組函式可針對輸入至 input 的程式碼,將之輸出到 {{HTMLElement("p")}} 元素。我們將透過此檔案說明基礎的物件語法。</p>
+
+<p>JavaScript 內的大多數東西,均是透過定義並初始設定變數來建立物件。</p>
+
+<p>現在, 請在自己的 oojs.html 檔案中、JavaScript 程式碼中加入下列程式碼,接著儲存並重新整理:</p>
+
+<pre class="brush: js">var person = {};</pre>
+
+<p>然後在瀏覽器中開啟 oojs.html, 再打開瀏覽器的開發者工具, 在 JavaScript 的控制台下, 輸入<code>person</code>, 並按下 Enter 鈕,就會得到下列結果:</p>
+
+<pre class="brush: js">[object Object]</pre>
+
+<p>恭喜, 你已經建立了自己的第一個物件。但這仍是空的物件,所以能做的事不多。接下來, 再如下所示, 幫 person 物件更新內容:</p>
+
+<pre class="brush: js">var person = {
+ name : ['Bob', 'Smith'],
+ age : 32,
+ gender : 'male',
+ interests : ['music', 'skiing'],
+ bio : function() {
+ alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
+ },
+ greeting: function() {
+ alert('Hi! I\'m ' + this.name[0] + '.');
+ }
+};
+</pre>
+
+<p>改完後同樣儲存 oojs.html、重新整理瀏覽器之後,再到控制台輸入 person, 將會看到新的結果:</p>
+
+<pre class="brush: js">person.name[0]
+person.age
+person.interests[1]
+person.bio()
+person.greeting()</pre>
+
+<p>現在你的物件裡面已經有了某些資料與功能,而且能透過某些簡易語法存取之。</p>
+
+<div class="note">
+<p><strong>注意:</strong>如果你無法完成上述步驟,可先和我們的版本比較一下。參閱 <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/introduction/oojs-finished.html">oojs-finished.html</a> (或觀看 <a href="http://mdn.github.io/learning-area/javascript/oojs/introduction/oojs-finished.html">實際執行</a>)。你最容易犯下的錯誤是在物件中的最後一個成員 (member)末端加上逗號,如此就會造成錯誤。</p>
+</div>
+
+<p>目前為止發生了什麼事呢?現在這個物件是由多個成員所構成,各個成員均有 1 個名稱 (如上述的 <code>name</code> 與 <code>age</code>) 以及 1 組數值 (如 <code>['Bob', 'Smith']</code> 與 <code>32</code>)。由名稱與數值構成的組合均以逗號區隔,而名稱與數值之間則以冒號隔開。語法應如下所示:</p>
+
+<pre class="brush: js">var objectName = {
+ member1Name : member1Value,
+ member2Name : member2Value,
+ member3Name : member3Value
+}</pre>
+
+<p>物件成員的數值可能是任何東西,像上述的範例物件就有 1 組字串、1 組數字、2 個陣列、2 組函式。前 4 組項目均為資料項目,可說是該物件的<strong>屬性</strong>。最後 2 組項目的功能則是用以指定物件對該筆資料所應進行的作業,可說是物件的<strong>函式 (Method)</strong>。</p>
+
+<p>類似這種物件即稱為「<strong>實字物件 (Object literal)</strong>」,按照字面上的意思寫出物件內容;與其相對的就是根據「類別」做出的物件實體。我們稍後會再說明。</p>
+
+<p>在傳送一系列結構化的相關資料項目時 (例如傳送請求至伺服器並置入資料庫中),就常常會透過實字物件的方式建立物件。另與「分別傳送多個項目」相較,送出單一物件當然效率更高,且當你想根據名稱找出各個項目時,更易於搭配陣列。</p>
+
+<h2 id="點記法_(Dot_notation)">點記法 (Dot notation)</h2>
+
+<p>你可透過點記法 (Dot notation) 存取物件的屬性與函式。物件名稱 (這裡是 person) 作為<strong>命名空間 (Namespace)</strong> —為了能存取物件所<strong>封裝</strong>的所有東西,這也是必須首先輸入的項目。接著你寫一個「點」以及你所想存取的項目,可能是簡單屬性的名稱、陣列屬性的項目,又或是針對物件函式之一的呼叫。舉例來說:</p>
+
+<pre class="brush: js">person.age
+person.interests[1]
+person.bio()</pre>
+
+<h3 id="子命名空間">子命名空間</h3>
+
+<p>甚至可以將物件成員的數值轉為另一個物件。舉例來說,你可將名稱成員從</p>
+
+<pre class="brush: js">name : ['Bob', 'Smith'],</pre>
+
+<p>改變為</p>
+
+<pre class="brush: js">name : {
+ first : 'Bob',
+ last : 'Smith'
+},</pre>
+
+<p>我們這裡以極高效率建立了子命名空間。看起來複雜但其實不然。若要存取這些項目,你只要透過另一個點,將 onto the end 的額外步驟串連起來即可。如下所示:</p>
+
+<pre class="brush: js">person.name.first
+person.name.last</pre>
+
+<p><strong>重要:</strong>現在你必須看過自己的函式碼,將實例</p>
+
+<pre class="brush: js">name[0]
+name[1]</pre>
+
+<p>改變為</p>
+
+<pre class="brush: js">name.first
+name.last</pre>
+
+<p>否則你的函式就不能運作了。</p>
+
+<h2 id="括弧記法_(Bracket_notation)">括弧記法 (Bracket notation)</h2>
+
+<p>括弧記法 (Bracket notation) 是另個存取物件屬性的方法。之前的:</p>
+
+<pre class="brush: js">person.age
+person.name.first</pre>
+
+<p>可寫成</p>
+
+<pre class="brush: js">person['age']
+person['name']['first']</pre>
+
+<p>這很像在陣列中存取項目的方法。其實基本上是一樣的東西 ─ 但前者是透過指數  (index number) 選擇項目;括弧記法則是透過各成員數值相關的名稱來選擇項目。因此物件有時亦稱作<strong>「相聯陣列 (Associative array)」</strong>;也就是說,其「將字串對應到數值」的方式,與陣列「將數字對應到數值」的方式相同。</p>
+
+<h2 id="設定物件成員">設定物件成員</h2>
+
+<p>到目前為止,我們只說明了檢索 (或<strong>取得</strong>) 物件成員。你也可以簡單宣告你所要設定的成員 (用點或括弧記法均可),設定 (<strong>更新</strong>) 物件成員的數值,如下:</p>
+
+<pre class="brush: js">person.age = 45
+person['name']['last'] = 'Cratchit'</pre>
+
+<p>試著輸入下列程式碼,再次取得成員之後看看變更的結果:</p>
+
+<pre class="brush: js">person.age
+person['name']['last']</pre>
+
+<p>設定成員不只是更新現有屬性與函式的數值,也可以建立全新的成員,如下:</p>
+
+<pre class="brush: js">person['eyes'] = 'hazel'
+person.farewell = function() { alert("Bye everybody!") }</pre>
+
+<p>現在可以測試自己的新成員了:</p>
+
+<pre class="brush: js">person['eyes']
+person.farewell()</pre>
+
+<p>此外,括弧記法不僅可動態設定成員數值,亦可設定成員名稱。假設使用者可在自己的人事資料中儲存自訂的數值類型,例如鍵入成員名稱與數值為 2 組文字輸入項,就會類似:</p>
+
+<pre class="brush: js">var myDataName = nameInput.value
+var myDataValue = nameValue.value</pre>
+
+<p>接著可將此新的成員名稱與數值加進 <code>person</code> 這個物件:</p>
+
+<pre class="brush: js">person[myDataName] = myDataValue</pre>
+
+<p>若要測試,可將下列程式碼加進自己的程式碼,加在宣告玩 <code>person</code> 物件的大括號後:</p>
+
+<pre class="brush: js">var myDataName = 'height'
+var myDataValue = '1.75m'
+person[myDataName] = myDataValue</pre>
+
+<p>現在儲存並重新整理,將下列輸入你的文字輸入項中:</p>
+
+<pre class="brush: js">person.height</pre>
+
+<p>因為點記法只接受字母表示的成員名稱,不能是指向名稱的變數值,所以並無法使用。</p>
+
+<h2 id="這個「this」是什麼?">這個「this」是什麼?</h2>
+
+<p>你可能注意到我們函式有怪怪的地方。看看以下範例:</p>
+
+<pre class="brush: js">greeting: function() {
+ alert('Hi! I\'m ' + this.name.first + '.');
+}</pre>
+
+<p>你可能會想這個「this」是幹嘛用的。「this」是指目前寫入程式碼的物件;所以此範例的 <code>this </code>就等於 <code>person</code>。那又為何不寫 <code>person</code> 就好呢?如同你在〈<a href="/zh-TW/docs/Learn/JavaScript/Objects/Object-oriented_JS">初學者的物件導向 JavaScript</a>〉一文中所看過的,當我們開始設定建構子等東西時,有用的「<code>this</code>」就可在成員內文改變時 (例如 2 個不同 <code>person</code> 物件實例可能具備不同的名稱,但打招呼時仍要使用自己的名稱),確保仍使用了正確的值。</p>
+
+<p>先用簡化的一對 person 物件說明:</p>
+
+<pre class="brush: js">var person1 = {
+ name : 'Chris',
+ greeting: function() {
+ alert('Hi! I\'m ' + this.name + '.');
+ }
+}
+
+var person2 = {
+ name : 'Brian',
+ greeting: function() {
+ alert('Hi! I\'m ' + this.name + '.');
+ }
+}</pre>
+
+<p>此範例中的函式碼雖然完全一樣,但 <code>person1.greeting()</code> 將輸出「Hi! I'm Chris.」;<code>person2.greeting()</code> 則會呈現「Hi! I'm Brian.」。如我們剛剛說過的,「<code>this」等於「已於內部放置程式碼」的物件</code>。如果你是依字面意義寫出物件,那可能沒什麼感覺,但如果你是用動態方式產生物件 (例如使用建構子) 的話,就能明顯感覺到方便之處了。再看下去你更清楚原因。</p>
+
+<h2 id="其實你一直在使用物件">其實你一直在使用物件</h2>
+
+<p>隨著你看完這些範例,你應該會覺得跟自己使用的點記法很類似。這是因為你整個課程都在使用點記法。每次我們透過內建的瀏覽器 API 或 JavaScript 物件寫出範例時,我們就是在用物件;因為這些功能也就是以本文提及完全相同的物件結構所寫成。即便是更複雜的範例也是一樣。</p>
+
+<p>所以當你使用字串函式如下:</p>
+
+<pre class="brush: js">myString.split(',');</pre>
+
+<p>你就是在使用 <code><a href="/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></code> 類別實例可用的方法。每次只要你在程式碼中建立字串,該字串就會自動建立成為 <code>String</code> 的實例,並具備有多個常見的方法與屬性。</p>
+
+<p>若你透過下列程式碼存取文件物件模型 (DOM):</p>
+
+<pre class="brush: js">var myDiv = document.createElement('div');
+var myVideo = document.querySelector('video');</pre>
+
+<p>你也就在使用 <code><a href="/zh-TW/docs/Web/API/Document">Document</a></code> 類別實例上的函式。當載入網頁時,就會建立 <code>Document</code> 的實例,亦所謂的 <code>document</code>,將呈現整個網頁的架構、內容,以及其他功能 (如網址)。同樣的,這代表其上已有多個常見的函式\屬性。</p>
+
+<p>同理可證,目前你在使用的許多物件\API (如 <code><a href="/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></code><code>、<a href="/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Math">Math</a></code> 等) 也都是類似情形。</p>
+
+<p>另該注意的是,內建的物件\API 不見得會自動建立物件實例。像以 <a href="/zh-TW/docs/Web/API/Notifications_API">Notifications API</a>  (它可以幫助你使用現代瀏覽器向使用者發送通知 ) 為例,就需要你針對想要觸發的通知,使用建構子逐一建立新的物件實例。試著將下列程式碼丟進你的 JavaScript 主控台:</p>
+
+<pre class="brush: js">var myNotification = new Notification('Hello!');</pre>
+
+<p>我們會在後續文章中說明建構子 (Constructor)。</p>
+
+<div class="note">
+<p><strong>注意:</strong>可思考一下物件「訊息傳遞」的溝通方式。當某個物件需要其他物件執行其他作業時,往往會透過其函式之一傳送訊息給其他物件並等待回應。這也是我們所謂的回傳值。</p>
+</div>
+
+<h2 id="摘要">摘要</h2>
+
+<p>恭喜你已經快讀完我們第一篇 JS 物件的文章了。你應該已經知道該如何使用 JavaScript 中的物件,並建立自己的簡單物件了。你也應該了解物件在儲存相關資料的好用之處。如果你將 <code>person</code> 物件中的所有屬性與函式,當做個別的變數與函式並試著追蹤,肯定吃力不討好;且其他具備相同名稱的變數與函式也可能發生問題。「物件」讓我們能在其封包中安全的與資訊相互區隔。</p>
+
+<p>下一篇文章將說明「物件導向程式設計 (OOP)」理論,並了解相關技術是如何用於 JavaScript 之中。</p>
+
+<p>{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}</p>
diff --git a/files/zh-tw/learn/javascript/objects/index.html b/files/zh-tw/learn/javascript/objects/index.html
new file mode 100644
index 0000000000..aa4b296a95
--- /dev/null
+++ b/files/zh-tw/learn/javascript/objects/index.html
@@ -0,0 +1,42 @@
+---
+title: JavaScript 物件介紹
+slug: Learn/JavaScript/Objects
+translation_of: Learn/JavaScript/Objects
+---
+<div>{{LearnSidebar}}</div>
+
+<p class="summary">在 JavaScript 裡面,從諸如字串與陣列的核心功能、到以 JavaScript 建構的瀏覽器 API,大部分的東西都可算是「物件 (Object)」。你甚至可建立自己的物件,將相關函式與變數封裝 (Encapsulate) 為有效封包,並可作為多樣的資料容器 (Data container)。如果你想更精進既有的程式語言知識,就必須了解 JavaScript 的「物件導向 (Object-Oriented;OO)」本質。為此,我們設計了相關文章來協助你更進一步。本文將先說明物件理論和語法的細節,再引導你建立自己的物件。</p>
+
+<h2 id="必備條件">必備條件</h2>
+
+<p>在開始閱讀本文之前,你應該已經對 HTML 與 CSS 有一定程度的認識。建議你先看過〈<a href="https://developer.mozilla.org/zh-TW/docs/Web/Guide/HTML/Introduction">HTML 介紹</a>〉以及〈<a href="https://developer.mozilla.org/zh-TW/docs/Learn/CSS/Introduction_to_CSS">CSS 介紹</a>〉,再開始了解 JavaScript。</p>
+
+<p>你也應該已經初步了解過 JavaScript 基本概念,再進一步閱讀 JavaScript 物件。所以另請先看過〈<a href="/zh-TW/docs/Learn/JavaScript/First_steps">JavaScript 的第一步</a>〉與〈<a href="/zh-TW/docs/Learn/JavaScript/Building_blocks">JavaScript 基礎要件</a>〉。</p>
+
+<div class="note">
+<p><strong>注意:</strong>如果你在使用的桌機\平板\其他裝置,無法讓你建立自己的檔案,則可透過如 <a href="http://jsbin.com/">JSBin</a> 或 <a href="https://thimble.mozilla.org/">Thimble</a> 的線上編碼程式,來體驗 (大多數的) 範例程式碼。</p>
+</div>
+
+<h2 id="指南">指南</h2>
+
+<dl>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/Objects/Basics">物件基本概念</a></dt>
+ <dd>第一篇主述 JavaScript 物件。我們將說明基本的 JavaScript 物件語法,並重新講解某些先前已經說過的 JavaScript 功能,也會再提及許多物件是你現正使用中的功能。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/Objects/Object-oriented_JS">適合初學者的 OO JaveScript</a></dt>
+ <dd>說明過基本概念之後,就會將重點放在物件導向的 JavaScript (OOJS) 本質上。本文會先介紹 OO 程式設計的基礎理論,再說明 JavaScript 是如何透過建構子 (Constructor) 函式模擬物件類別並建立物件實體 (Instance)。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/Objects/Object_prototypes">物件原型</a></dt>
+ <dd>原型 (Prototype) 是 JavaScript 物件用以互相繼承功能的機制,且其與典型 OO 程式語言中的繼承機制有所不同。本文將探討其中相異性、說明原型鏈的運作方式,並透過原型屬性將函式新增至現有建構子。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/Objects/Inheritance">JavaScript 中的繼承</a></dt>
+ <dd>再說明了 JavaScript 大多數的 OO 特性之後,將說明應如何建立「子」物件類別 (建構子) 並繼承其「母」類別的功能。此外,我們將針對你可能使用 OOJS 的時機提供建言。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/Objects/JSON">利用 JSON 資料</a></dt>
+ <dd>JavaScript Object Notation (JSON) 為標準格式,用以將「結構化資料 (Structured data)」呈現為 JavaScript 物件,並常用於網站之間呈現\傳輸資料 (如從伺服器傳送資料到用戶端,以於網頁上顯示內容)。你一定會常接觸到類似情形,所以本文將提供用 JavaScript 搭配 JSON 開發時的所有資訊,包含在 JSON 物件中存取資料項目,以及撰寫你自己的 JSON。</dd>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/Objects/Object_building_practice">物件打造實例</a></dt>
+ <dd>前幾篇文章帶領你看過基本的 JavaScript 物件理論和語法細節,幫你打下厚實的基礎。而本文要讓你實際操作,透過更多實例自訂出 JavaScript 物件,讓你享受多采多姿的學習過程 (讓你寫出彩色的跳跳球喔)。</dd>
+</dl>
+
+<h2 id="評量">評量</h2>
+
+<dl>
+ <dt><a href="/zh-TW/docs/Learn/JavaScript/Objects/Adding_bouncing_balls_features">為彩色跳跳球展示範例新增其他功能</a></dt>
+ <dd>在此評量中,你已經先寫出了跳跳球範例。接著要讓你新增其他有趣的功能。</dd>
+</dl>
diff --git a/files/zh-tw/learn/javascript/objects/inheritance/index.html b/files/zh-tw/learn/javascript/objects/inheritance/index.html
new file mode 100644
index 0000000000..f9db84dae8
--- /dev/null
+++ b/files/zh-tw/learn/javascript/objects/inheritance/index.html
@@ -0,0 +1,210 @@
+---
+title: JavaScript 中的「繼承」
+slug: Learn/JavaScript/Objects/Inheritance
+translation_of: Learn/JavaScript/Objects/Inheritance
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects")}}</div>
+
+<p class="summary">在解釋過大部分的 OOJS 細節之後,本文將說明該如何建立「子」物件類別 (建構子),並從其「母」類別繼承功能。此外,也將建議開發者應於何時、於何處使用 OOJS。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">必備條件:</th>
+ <td>基本的電腦素養、已了解 HTML 與 CSS 基本概念、熟悉 JavaScript 基礎 (可參閱〈<a href="/en-US/docs/Learn/JavaScript/First_steps">First steps</a>〉與〈<a href="/en-US/docs/Learn/JavaScript/Building_blocks">Building blocks</a>〉) 與 OOJS 的基礎 (可參閱〈<a href="/en-US/docs/Learn/JavaScript/Object-oriented/Introduction">Introduction to objects</a>〉)。</td>
+ </tr>
+ <tr>
+ <th scope="row">主旨:</th>
+ <td>了解應如何建構 JavaScript 中的繼承。</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="原型繼承">原型繼承</h2>
+
+<p>目前為止,我們看過幾個繼承的實作範例:原型鍊的運作方式,以及繼承的成員如何形成原型鍊。但這些大部分都與內建的瀏覽器函式有關。那我們又該如何在 JavaScript 建立物件且由其他物件繼承而來呢?</p>
+
+<p>如稍早的系列文章中所述,某些人認為 JavaScript 並非真正的物件導向 (OO) 語言。在「典型 OO」中,你必須定義特定的類別物件,才能定義哪些類別所要繼承的類別 (可參閱〈<a href="http://www.tutorialspoint.com/cplusplus/cpp_inheritance.htm">C++ inheritance</a>〉了解簡易範例)。JavaScript 則使用不同的系統 —「繼承」的物件並不會一併複製功能過來,而是透過原型鍊連接其所繼承的功能,亦即所謂的原型繼承 (<strong>Prototypal inheritance</strong>)。</p>
+
+<p>就透過範例了解此一概念吧。</p>
+
+<h2 id="入門">入門</h2>
+
+<p>首先將 <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/advanced/oojs-class-inheritance-start.html">oojs-class-inheritance-start.html</a> 檔案 (亦可參考<a href="http://mdn.github.io/learning-area/javascript/oojs/advanced/oojs-class-inheritance-start.html">實際執行</a>) 複製到本端磁碟。可在裡面找到本課程一直沿用的 <code>Person()</code> 建構子範例,但這裡有些許不同,也就是該建構子只定義了屬性:</p>
+
+<pre class="brush: js">function Person(first, last, age, gender, interests) {
+ this.name = {
+ first,
+ last
+ };
+ this.age = age;
+ this.gender = gender;
+ this.interests = interests;
+};</pre>
+
+<p>這些函式均已定義於建構子的原型之上,例如:</p>
+
+<pre class="brush: js">Person.prototype.greeting = function() {
+ alert('Hi! I\'m ' + this.name.first + '.');
+};</pre>
+
+<p>假設要建立一個像前面 OO 定義中說過的 <code>Teacher</code> 類別,且除了繼承 <code>Person</code> 的所有成員,還要包含:</p>
+
+<ol>
+ <li>新的 <code>subject</code> 屬性,可包含老師所傳授的科目。</li>
+ <li>更新過的 <code>greeting()</code> 函式,要比標準的 <code>greeting()</code> 函式更正式一點,更適合老師在校對學生使用。</li>
+</ol>
+
+<h2 id="定義_Teacher()_建構子函式">定義 Teacher() 建構子函式</h2>
+
+<p>首先必須建立 <code>Teacher()</code> 建構子,將下列程式碼加到現有程式碼之下:</p>
+
+<pre class="brush: js">function Teacher(first, last, age, gender, interests, subject) {
+ Person.call(this, first, last, age, gender, interests);
+
+ this.subject = subject;
+}</pre>
+
+<p>這看起來和 Person 建構子有許多地方類似,但比較奇怪的就是之前沒看過的 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">call()</a></code> 函式。此函式基本上可讓你呼叫在其他地方定義的函數,而非目前內文 (context) 中定義的函式。當執行函式時,第一個參數用來指定你要使用 <code>this</code> 值,其他參數則指定應該傳送到該函式的參數。</p>
+
+<div class="note">
+<p><strong>注意:</strong>我們此範例中建立新的物件實例時,會指定所要繼承的屬性。但必須注意的是,即使實例不需將屬性指定為參數,你還是必須在建構子中將屬性指定為參數  (在建立物件時,你可能獲得設定為隨意值的屬性)。</p>
+</div>
+
+<p>所以這裡可在 <code>Teacher()</code> 建構子函式之內有效執行 <code>Person() </code>建構子函式 (如上述),藉以在 <code>Teacher()</code> 之內定義相同的屬性,但使用的是傳送到 <code>Teacher()</code> 的屬性值,而非 <code>Person()</code> 的屬性值 (我們將 <code>this</code> 值設為簡單的「<code>this」並</code>傳送到 <code>call()</code>,代表這個 <code>this</code> 是 <code>Teacher()</code> 的函式)。</p>
+
+<p>建構子的最後一行則定義了新的 <code>subject</code> 屬性,代表只有老師具備,一般人不會有。</p>
+
+<p>我們也可以單純這樣做:</p>
+
+<pre class="brush: js">function Teacher(first, last, age, gender, interests, subject) {
+ this.name = {
+ first,
+ last
+ };
+ this.age = age;
+ this.gender = gender;
+ this.interests = interests;
+ this.subject = subject;
+}</pre>
+
+<p>但這樣只是重新定義了新的屬性,而不是繼承自 <code>Person() 而來,所以無法達到我們預設的目標,也需要更多程式碼才能達成。</code></p>
+
+<h2 id="設定_Teacher()_的原型與建構子參考">設定 Teacher() 的原型與建構子參考</h2>
+
+<p>到目前為止發現一個問題:我們定義了新的建構子,但預設只有 1 個空白的 <code>prototype</code> 屬性。接著要讓 <code>Teacher()</code> 繼承 <code>Person()</code> 原型中所定義的函式,該怎麼做呢?</p>
+
+<ol>
+ <li>繼續在現有程式碼下方加入:
+ <pre class="brush: js">Teacher.prototype = Object.create(Person.prototype);</pre>
+ 這裡再次用好朋友 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create">create()</a></code> 解救。我們透過 <code>create()</code> 並搭配等同於 <code>Person.prototype</code> 的原型,建立新的 <code>prototype</code> 屬性值 (它本身就是物件,包含屬性與函式) ,並將之設定為 <code>Teacher.prototype</code> <code>的值。也就是說</code> <code>Teacher.prototype</code> 現在會繼承 <code>Person.prototype</code> 上的所有可用函式。</li>
+ <li>此外,基於我們的繼承方式,<code>Teacher()</code> <code>prototype</code> 的建構子屬性目前設定為 <code>Person()。可參閱</code> <a href="https://stackoverflow.com/questions/8453887/why-is-it-necessary-to-set-the-prototype-constructor">Stack Overflow post</a> 進一步了解原因。可先儲存自己的程式碼、在瀏覽器中載入頁面,再將下列程式碼輸入至 JavaScript 主控台以驗證:
+ <pre class="brush: js">Teacher.prototype.constructor</pre>
+ </li>
+ <li>這樣可能會產生問題,所以要設定正確。你可回到自己的原始碼並在最下方加入下列程式碼:
+ <pre class="brush: js">Teacher.prototype.constructor = Teacher;</pre>
+ </li>
+ <li>如果儲存並重新整理之後,只要輸入 <code>Teacher.prototype.constructor</code> 應該就會回傳 <code>Teacher()</code>。</li>
+</ol>
+
+<h2 id="給_Teacher()_新的_greeting()_函式">給 Teacher() 新的 greeting() 函式</h2>
+
+<p>接著必須在 <code>Teacher()</code> 建構子上定義新的 <code>greeting()</code> 函式。</p>
+
+<p>最簡單的方法就是在 <code>Teacher()</code> 的原型上定義此函式。將下列加入程式碼最底部:</p>
+
+<pre class="brush: js">Teacher.prototype.greeting = function() {
+ var prefix;
+
+ if(this.gender === 'male' || this.gender === 'Male' || this.gender === 'm' || this.gender === 'M') {
+ prefix = 'Mr.';
+ } else if(this.gender === 'female' || this.gender === 'Female' || this.gender === 'f' || this.gender === 'F') {
+ prefix = 'Mrs.';
+ } else {
+ prefix = 'Mx.';
+ }
+
+ alert('Hello. My name is ' + prefix + ' ' + this.name.last + ', and I teach ' + this.subject + '.');
+};</pre>
+
+<p>這樣就會顯示老師的問候語,也會針對老師的性別使用合適的稱呼,可用於條件陳述式。</p>
+
+<h2 id="簡易範例">簡易範例</h2>
+
+<p>現在你已經輸入所有程式碼了,可以試著用<code>Teacher()</code> 建立物件實例。將下列 (或是你想用的類似程式碼) 加入現有程式碼的底部:</p>
+
+<pre class="brush: js">var teacher1 = new Teacher('Dave', 'Griffiths', 31, 'male', ['football', 'cookery'], 'mathematics');</pre>
+
+<p>儲存並重新整理之後,試著存取新 <code>teacher1</code> 物件的屬性語函式,例如:</p>
+
+<pre class="brush: js">teacher1.name.first;
+teacher1.interests[0];
+teacher1.bio();
+teacher1.subject;
+teacher1.greeting();</pre>
+
+<p>這樣應該運作無虞。前 3 行的存取成員即繼承自一般 <code>Person()</code> 建構子 (類別)。最後 2 行的存取成員只能用於特定的 <code>Teacher()</code> 建構子 (類別) 之上。</p>
+
+<div class="note">
+<p><strong>注意:</strong>如果你無法進行到現有進度,可比較自己與<a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/advanced/oojs-class-inheritance-finished.html">完整版本</a> (亦可看<a href="http://mdn.github.io/learning-area/javascript/oojs/advanced/oojs-class-inheritance-finished.html">實際執行</a>的情形) 的程式碼。</p>
+</div>
+
+<p>這裡所提的技巧,當然不是在 JavaScript 建立繼承類別的唯一方法,但足以堪用。並可讓你了解應如何於 JavaScript 實作繼承。</p>
+
+<p>你可能也想看看某些新的 {{glossary("ECMAScript")}} 功能,可更簡潔的在 JavaScript 中繼承 (參閱 <a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a>)。但由於這些功能尚未廣泛支援其他瀏覽器,這裡先略過不提。本系列文章中提到的其他程式碼,均可回溯支援到 IE9 或更早版本。當然還是有辦法支援更舊的版本。</p>
+
+<p>一般方法就是使用 JavaScript 函式庫,且最常見的就是簡單集結可用的功能,更快、更輕鬆的完成繼承。例如 <a href="http://coffeescript.org/#classes">CoffeeScript</a> 即提供了 <code>class</code><code>、extends</code> 等等。</p>
+
+<h2 id="進階習題">進階習題</h2>
+
+<p>在<a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS#Object-oriented_programming_from_10000_meters">〈OOP 理論〉段落</a>中,我們也納入了 <code>Student</code> 類別並繼承了 <code>Person</code> 的所有功能,此外也提供不同的 <code>greeting()</code> 函式,且較 <code>Teacher</code> 的問候語沒那麼正式。在看了該段落中的學生問候語之後,可試著實作自己的 <code>Student()</code> 建構子,並繼承 <code>Person()</code>, 的所有功能,再實作不同的 <code>greeting()</code> 函式。</p>
+
+<div class="note">
+<p><strong>注意:</strong>如果你無法進行到現有進度,可參考<a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/advanced/oojs-class-inheritance-student.html">完成版本</a> (亦可看<a href="http://mdn.github.io/learning-area/javascript/oojs/advanced/oojs-class-inheritance-student.html">實際執行</a>的情形)。</p>
+</div>
+
+<h2 id="物件成員摘要">物件成員摘要</h2>
+
+<p>簡單來說,你基本上需要考量 3 種類型的屬性\函式:</p>
+
+<ol>
+ <li>已於建構子函式中定義,會交給物件實體的屬性\函式。這應該很容易處理。在你自己的程式碼中,就是透過 <code>this.x = x</code> 類別行並在建構子中定義的成員;在瀏覽器程式碼中,就是僅限物件實體可用的成員 (一般是透過 <code>new</code> 關鍵字並呼叫建構子所建立,例如 <code>var myInstance = new myConstructor()</code>)。</li>
+ <li>直接在建構子上定義,並僅能用於該建構子的屬性\函式。這類屬性\函式往往只能用於內建瀏覽器物件之上,並直接「鍊接」至建構子 (而非實例) 以利識別,例如 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys">Object.keys()</a></code>。</li>
+ <li>定義於建構子原型上的屬性\函式,交由所有的實例繼承,亦繼承了物件類別。這類屬性\函式包含建構子原型屬性之上定義的所有成員,例如 <code>myConstructor.prototype.x()</code>。</li>
+</ol>
+
+<p>如果你不確定到底屬於上述的哪一個,也別擔心。現在你還在學習階段,往後定會熟能生巧。</p>
+
+<h2 id="在_JavaScript_中使用繼承的時機?">在 JavaScript 中使用繼承的時機?</h2>
+
+<p>看到這裡,你心裡應該覺得很複雜。沒錯。「原型」與「繼承」可說是 JavaScript 最複雜的概念之二,但許多 JavaScript 的強大功能與彈性,均來自於其物件結構與繼承,也值得你了解運作方式。</p>
+
+<p>不論是使用 WebAPI 的多樣功能,或是你在字串、陣列等所呼叫的函式\屬性 (定義於內建瀏覽器物件之上),你都可以不斷繼承下去。</p>
+
+<p>在自己的程式碼裡,特別是剛接觸或小型專案時,你用繼承的頻率可能沒那麼高。若沒真正需要,只是「為使用而使用」繼承,老實說只是浪費時間。但隨著程式碼規模越來越大,你就會找到使用的時間。如果你發現自己開始建立類似功能的多個物件時,就可先建立通用的物件類型,來概括所有共用的功能,並在特定物件類型中繼承這些功能,既方便又有效率。</p>
+
+<div class="note">
+<p><strong>注意:</strong>基於 JavaScript 運作的方式 (如原型鍊等),物件之間的功能共享一般稱為<strong>「</strong><strong>委託 (Delegation)」</strong>,即特定物件將功能委託至通用物件類型。「委託」其實比繼承更精確一點。因為「所繼承的功能」並不會複製到「進行繼承的物件」之上,卻是保留在通用物件之中。</p>
+</div>
+
+<p>當使用繼承時,建議你不要設定太多層的繼承關係,並時時留意你所定義的函式與屬性。在開始寫程式碼時,你可能會暫時修改內建瀏覽器物件的原型,除非你真的需要,否則儘量別這麼做。太多繼承可能連你自己都搞混,而且一旦需要除錯就會痛苦萬分。</p>
+
+<p>最後,物件可說是另一種形式的程式碼再利用,如同函式或迴圈一般,且有其專屬的角色與優點。如果你正建立一堆相關變數與函式,並要全部一起追蹤、封裝,就可以透過物件。你也能以物件方式傳送整個資料集合。而且上述兩種情況均不需使用建構子或繼承就能夠達成。如果你只需要某一物件的單一實作,那麼單純使用物件就好,完全不需要繼承。</p>
+
+<h2 id="摘要">摘要</h2>
+
+<p>本文為大家溫習了 OOJS 核心理論和語法。現在你應該了解 JavaScript 物件與 OOP 的基本概念、原型及原型繼承、建立類別 (建構子) 與物件實例的方法、為類別新增功能、建立從其他類別繼承而來的子類別。</p>
+
+<p>下篇文章就要來看看該如何搭配 JavaScript Object Notation (JSON),使用 JavaScript 物件的常見資料交換格式。</p>
+
+<h2 id="另可參閱">另可參閱</h2>
+
+<ul>
+ <li><a href="http://www.objectplayground.com/">ObjectPlayground.com</a> — 互動式學習網站,讓你了解物件。</li>
+ <li><a href="https://www.amazon.com/gp/product/193398869X/">Secrets of the JavaScript Ninja</a> 的第六章 — 進階 JavaScript 概念與技術的好書。第六章講述了原型與繼承的概念。此書有紙本與線上版。</li>
+ <li><a href="https://github.com/getify/You-Dont-Know-JS/blob/master/this%20&amp;%20object%20prototypes/README.md#you-dont-know-js-this--object-prototypes">You Don't Know JS: this &amp; Object Prototypes</a> — Kyle Simpson 絕佳 JavaScript 手冊系列的一部分。第五章特別深入講述了原型。我們透過本文為初學者提供簡易概念,但 Kyle 則說明得更深入、更精確。</li>
+</ul>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects")}}</p>
diff --git a/files/zh-tw/learn/javascript/objects/json/index.html b/files/zh-tw/learn/javascript/objects/json/index.html
new file mode 100644
index 0000000000..71a4a3776a
--- /dev/null
+++ b/files/zh-tw/learn/javascript/objects/json/index.html
@@ -0,0 +1,325 @@
+---
+title: 使用 JSON 資料
+slug: Learn/JavaScript/Objects/JSON
+tags:
+ - JSON
+translation_of: Learn/JavaScript/Objects/JSON
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects/Object_building_practice", "Learn/JavaScript/Objects")}}</div>
+
+<p class="summary">JavaScript Object Notation (JSON) 為將結構化資料 (structured data) 呈現為 JavaScript 物件的標準格式,常用於網站上的資料呈現、傳輸 (例如將資料從伺服器送至用戶端,以利顯示網頁)。你應該會常常遇到,因此本文將說明 JavaScript 搭配 JSON 時所應知道的觀念,包含如何在 JSON 物件中存取資料項目,並寫出你自己的 JSON。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">必要條件:</th>
+ <td>基礎的計算機素養、了解 HTML 與 CSS 的基本概念、熟悉 JavaScript (參閱〈<a href="/en-US/docs/Learn/JavaScript/First_steps">First steps</a>〉與〈<a href="/en-US/docs/Learn/JavaScript/Building_blocks">Building blocks</a>〉) 與 OOJS 基本概念 (參閱〈<a href="/en-US/docs/Learn/JavaScript/Object-oriented/Introduction">Introduction to objects</a>〉)。</td>
+ </tr>
+ <tr>
+ <th scope="row">主旨:</th>
+ <td>了解應如何使用 JSON 格式所儲存的資料,建立自己的 JSON 物件。</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="說真的,到底什麼是_JSON?">說真的,到底什麼是 JSON?</h2>
+
+<p>{{glossary("JSON")}} 是依照 JavaScript 物件語法的資料格式,經 <a href="https://en.wikipedia.org/wiki/Douglas_Crockford">Douglas Crockford</a> 推廣普及。雖然 JSON 是以 JavaScript 語法為基礎,但可獨立使用,且許多程式設計環境亦可讀取 (剖析) 並產生 JSON。</p>
+
+<p>JSON 可能是物件或字串。當你想從 JSON中讀取資料時,JSON可作為物件;當要跨網路傳送 JSON 時,就會是字串。這不是什麼大問題 —  JavaScript 提供全域 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON</a> 物件,其內的函式可進行切換。</p>
+
+<p>JSON 物件可儲存於其自有的檔案中,基本上就是副檔名為 <code>.json</code> 的文字檔案,以及 <code>application/json</code> 的 {{glossary("MIME type")}}。</p>
+
+<h3 id="JSON_的架構">JSON 的架構</h3>
+
+<p>我們剛提到「JSON 物件基本上就是 JavaScript 物件」,而這敘述在大多數情況下都對。如同標準的 JavaScript 物件,你當然可在 JSON 之內加入相同的基本資料類型,如字串、數字、陣列、布林值,以及其他物件,接著同樣能再建構出資料繼承,如:</p>
+
+<pre class="brush: json">{
+  "squadName" : "Super hero squad",
+  "homeTown" : "Metro City",
+  "formed" : 2016,
+  "secretBase" : "Super tower",
+ "active" : true,
+  "members" : [
+    {
+      "name" : "Molecule Man",
+      "age" : 29,
+      "secretIdentity" : "Dan Jukes",
+      "powers" : [
+        "Radiation resistance",
+        "Turning tiny",
+        "Radiation blast"
+      ]
+    },
+    {
+      "name" : "Madame Uppercut",
+      "age" : 39,
+      "secretIdentity" : "Jane Wilson",
+      "powers" : [
+        "Million tonne punch",
+        "Damage resistance",
+        "Superhuman reflexes"
+      ]
+    },
+    {
+      "name" : "Eternal Flame",
+      "age" : 1000000,
+      "secretIdentity" : "Unknown",
+      "powers" : [
+        "Immortality",
+        "Heat Immunity",
+        "Inferno",
+        "Teleportation",
+        "Interdimensional travel"
+      ]
+    }
+  ]
+}</pre>
+
+<p>舉例來說,如果將此物件載入至 JavaScript 程式並將之儲存為「<code>superHeroes</code>」變數,如同〈<a href="/en-US/docs/Learn/JavaScript/Objects/Basics">JavaScript 物件基本概念</a>〉一文中提過的,接著能以相同的  存取其內部的資料,如下:</p>
+
+<pre class="brush: js">superHeroes.hometown
+superHeroes["active"]</pre>
+
+<p>若要順著繼承往下存取資料,只要將必要的屬性名稱與陣列索引「鍊」在一起即可。舉例來說,如果要存取成員列表中的第二位英雄的第三項超能力,你必須:</p>
+
+<pre class="brush: js">superHeroes["members"][1]["powers"][2]</pre>
+
+<ol>
+ <li>首先要有變數名稱 — <code>superHeroes</code>。</li>
+ <li>要在變數中存取 <code>members</code> 屬性,所以用 <code>["members"]</code>。</li>
+ <li><code>members</code> 包含由物件產生陣列。我們要存取陣列中的第二個物件,所以用 <code>[1]</code>。</li>
+ <li>在此物件中,我們要存取 <code>powers</code> 屬性,所以用 <code>["powers"]</code>。</li>
+ <li>在 <code>powers</code> 屬性中有 1 個陣列具備所選超級英雄的能力。我們要選第三種能力,所以用 <code>[2]</code>。</li>
+</ol>
+
+<div class="note">
+<p><strong>注意:</strong>我們在 <a href="http://mdn.github.io/learning-area/javascript/oojs/json/JSONTest.html">JSONText.html</a> 範例 (參閱<a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/JSONTest.html">原始碼</a>) 的變數中,示範上述可用的 JSON。你可在自己瀏覽器的 JavaScript 主控台載入此程式碼,並存取變數中的資料。</p>
+</div>
+
+<h3 id="陣列作為_JSON">陣列作為 JSON</h3>
+
+<p>我們在上面提過「 JSON 物件基本上就是 JavaScript 物件,而這敘述在大多數情況下都對」。其中「在大多數情況下都對」的理由,就是因為陣列也可以是有效的 JSON 物件,例如:</p>
+
+<pre class="brush: json">[
+ {
+ "name" : "Molecule Man",
+ "age" : 29,
+ "secretIdentity" : "Dan Jukes",
+ "powers" : [
+ "Radiation resistance",
+ "Turning tiny",
+ "Radiation blast"
+ ]
+ },
+ {
+    "name" : "Madame Uppercut",
+    "age" : 39,
+    "secretIdentity" : "Jane Wilson",
+    "powers" : [
+      "Million tonne punch",
+      "Damage resistance",
+      "Superhuman reflexes"
+    ]
+  }
+]</pre>
+
+<p>上面程式碼絕對是有效的 JSON。你可用陣列指數為開頭來存取陣列項目,例如 <code>[0]["powers"][0]</code>。</p>
+
+<h3 id="其他附註">其他附註</h3>
+
+<ul>
+ <li>JSON 是純粹的資料格式 — 僅具備屬性,而無函式。</li>
+ <li>JSON 需要雙引號,才能使用\有效。所以最安全的方法就是以雙引號撰寫之。</li>
+ <li>單一個逗號或冒號放錯位置,也會讓 JSON 檔案出錯而無法運作。你應仔細檢視所有要使用的資料 (只要產生器程式能正確運作,由電腦產生的 JSON 也就不容易出錯)。你可透過如 <a href="http://jsonlint.com/">JSONLint</a> 的應用程式檢驗 JSON。</li>
+ <li>不限於陣列或物件,只要是符合標準 JSON 物件形式的任何資料,都可以夾帶進 JSON 檔案中。因此,單一字串或數字也可能是有效的 JSON 物件,但不一定有用就是了...</li>
+</ul>
+
+<h2 id="主動學習:完成_JSON_範例">主動學習:完成 JSON 範例</h2>
+
+<p>現在就試著在網站上,透過某些 JSON 資料完成範例吧。</p>
+
+<h3 id="入門">入門</h3>
+
+<p>在開始之前,先複製我們的 <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/heroes.html">heroes.html</a> 與 <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/style.css">style.css</a> 到你的本端硬碟中。後者包含某些簡易的 CSS 可塑造網頁風格;前者則提供極簡單主體 HTML:</p>
+
+<pre class="brush: html">&lt;header&gt;
+&lt;/header&gt;
+
+&lt;section&gt;
+&lt;/section&gt;</pre>
+
+<p>加上 {{HTMLElement("script")}} 元素,才能納入稍後會在此習題中寫出來的 JavaScript 程式碼。目前只有 2 行程式碼,用以取得 {{HTMLElement("header")}} 與 {{HTMLElement("section")}} 元素的參考,並將之儲存於變數之中:</p>
+
+<pre class="brush: js">var header = document.querySelector('header');
+var section = document.querySelector('section');</pre>
+
+<p>你可到 GitHub 上找到此 JSON 資料:<a href="https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json">https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json</a>。</p>
+
+<p>接著載入到頁面之中,並使用某些有趣的 DOM 操控 (DOM manipulation) 來顯示,如下:</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13857/json-superheroes.png" style="display: block; margin: 0 auto;"></p>
+
+<h3 id="載入我們的_JSON">載入我們的 JSON</h3>
+
+<p>若要將 JSON 載入至頁面,就要透過 {{domxref("XMLHttpRequest")}} API (通常稱為 <strong>XHR</strong>)。此是極好用的 JavaScript 物件,可讓網路請求透過 JavaScript (例如圖片、文字、JSON,甚至 HTML 片段) 來檢索伺幅器的資源,這也代表我們不需載入整個頁面,就能更新小部分的內容。如此可讓網頁反應速度更快;聽起來很棒吧?但可惜本文無法再深入講解更多細節。</p>
+
+<ol>
+ <li>一開始,我們先針對要在變數中檢索的 JSON 檔案,將其網址儲存起來。把下列程式碼加到你 JavaScript 程式碼的最下方:
+ <pre class="brush: js">var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';</pre>
+ </li>
+ <li>為了建立請求,我們必須透過 <code>new</code> 關鍵字,先從 <code>XMLHttpRequest</code> 建構子建立新的請求物件實例。把下列加到最後一行:
+ <pre class="brush: js">var request = new XMLHttpRequest();</pre>
+ </li>
+ <li>現在用 <code><a href="/en-US/docs/Web/API/XMLHttpRequest/open">open()</a></code> 函式開啟新的請求。加入下列程式碼:
+ <pre class="brush: js">request.open('GET', requestURL);</pre>
+
+ <p>這樣就顧到至少 2 個參數。當然也有其他參數可選擇。但這個簡易範例只需要 2 個強制參數:</p>
+
+ <ul>
+ <li>在設立網路請求時,應使用 HTTP 函式。因為這裡只要檢索簡單的資料,所以用 <code><a href="/en-US/docs/Web/HTTP/Methods/GET">GET</a></code> 就可以。</li>
+ <li>URL 提供請求目的地 — 這也就是我們剛剛儲存的 JSON 檔案網址。</li>
+ </ul>
+ </li>
+ <li>接著加入下面 2 行程式碼。我們為 JSON 設定了 <code><a href="/en-US/docs/Web/API/XMLHttpRequest/responseType">responseType</a></code>,告知伺服器應回傳 JSON 物件,再以 <code><a href="/en-US/docs/Web/API/XMLHttpRequest/send">send()</a></code> 函式傳送請求:
+ <pre class="brush: js">request.responseType = 'json';
+request.send();</pre>
+ </li>
+ <li>最後就是等待由伺服器所回傳的反應,再接著處理。把下列程式碼加入現有程式碼的最下方:
+ <pre class="brush: js">request.onload = function() {
+ var superHeroes = request.response;
+ populateHeader(superHeroes);
+ showHeroes(superHeroes);
+}</pre>
+ </li>
+</ol>
+
+<p>在這裡,我們將所獲得的響應 (可到 <code><a href="/en-US/docs/Web/API/XMLHttpRequest/response">response</a></code> 屬性中找到) 儲存到 <code>superHeroes</code> 變數之中。此變數現在會納入我們的 JSON。接著再把此 JSON 檔案送到 2 個函式呼叫。第一個函式呼叫會將正確資料填入 &lt;<code>header&gt;</code>;第二個函式呼叫則會為團隊中的各個英文建立資訊卡,再插入至 <code>&lt;section&gt;</code> 內。</p>
+
+<p>當於請求物件上觸發載入事件時,會執行一個事件處理器。我們就將程式碼包裹至此處理器之中 (參閱 <code><a href="/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload">onload</a></code>) — 只要成功回傳響應,就會觸發載入事件。之所以這樣做,是為了確保當我們要以 <code>request.response</code> 進行某件事時,此 <code>request.response</code> 絕對可用。</p>
+
+<h3 id="產生標頭">產生標頭</h3>
+
+<p>現在檢索過了 JSON 資料,接著就寫出上面參照過的 2 個函式來利用 JSON 資料吧。首先將下列函式定義加到先前的程式碼中:</p>
+
+<pre class="brush: js">function populateHeader(jsonObj) {
+ var myH1 = document.createElement('h1');
+ myH1.textContent = jsonObj['squadName'];
+ header.appendChild(myH1);
+
+ var myPara = document.createElement('p');
+ myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed'];
+ header.appendChild(myPara);
+}</pre>
+
+<p>我們已經將參數命名為 <code>jsonObj</code>,所以在這個函式之內就要用 jsonObj 呼叫此參數。這裡先以 <code><a href="/en-US/docs/Web/API/Document/createElement">createElement()</a></code> 建立 1 組 {{HTMLElement("h1")}} 元素、將其 <code><a href="/en-US/docs/Web/API/Node/textContent">textContent</a></code> 指定為 JSON 的 <code>squadName</code> 屬性、透過 <code><a href="/en-US/docs/Web/API/Node/appendChild">appendChild()</a></code> 將之附加到標頭。接著 {{HTMLElement("p")}} 元素依樣畫葫蘆一遍:建立、設定其文字內容、附加到標頭。唯一不同之處,就是將該文字設定為 1 組串接字串 (Concatenated string),其內包含 JSON 的 <code>homeTown</code> 與 <code>formed</code> 屬性。</p>
+
+<h3 id="建立超級英雄的資訊卡片">建立超級英雄的資訊卡片</h3>
+
+<p>現在將下列函式加到程式碼底端,用以建立並顯示超級英雄的卡片:</p>
+
+<pre class="brush: js">function showHeroes(jsonObj) {
+ var heroes = jsonObj['members'];
+
+ for(i = 0; i &lt; heroes.length; i++) {
+ var myArticle = document.createElement('article');
+ var myH2 = document.createElement('h2');
+ var myPara1 = document.createElement('p');
+ var myPara2 = document.createElement('p');
+ var myPara3 = document.createElement('p');
+ var myList = document.createElement('ul');
+
+ myH2.textContent = heroes[i].name;
+ myPara1.textContent = 'Secret identity: ' + heroes[i].secretIdentity;
+ myPara2.textContent = 'Age: ' + heroes[i].age;
+ myPara3.textContent = 'Superpowers:';
+
+ var superPowers = heroes[i].powers;
+ for(j = 0; j &lt; superPowers.length; j++) {
+ var listItem = document.createElement('li');
+ listItem.textContent = superPowers[j];
+ myList.appendChild(listItem);
+ }
+
+ myArticle.appendChild(myH2);
+ myArticle.appendChild(myPara1);
+ myArticle.appendChild(myPara2);
+ myArticle.appendChild(myPara3);
+ myArticle.appendChild(myList);
+
+ section.appendChild(myArticle);
+ }
+}</pre>
+
+<p>我們先把 JSON 的 <code>members</code> 屬性儲存到新的變數中。此陣列所具備的多個物件,均包含了各個超級英雄的資訊。</p>
+
+<p>接著我們以 <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#The_standard_for_loop">for 迴圈</a>循環陣列中的各個物件。針對每個物件都會:</p>
+
+<ol>
+ <li>建立數個新的元素:1 組 <code>&lt;article&gt;</code>、1 組 <code>&lt;h2&gt;、3 組</code> <code>&lt;p&gt;、1 組</code> <code>&lt;ul&gt;。</code></li>
+ <li>讓 &lt;h2&gt; 納入目前超級英雄的 <code>name</code>。</li>
+ <li>接著 3 個段落分別是英雄的 <code>secretIdentity</code>、<code>age、Superpowers</code>,在列表中帶出相關資訊。</li>
+ <li>另以新變數 <code>superPowers</code> 儲存 <code>powers</code> 屬性 — 其中包含 1 組陣列以列出目前英雄的超能力。</li>
+ <li>再用另一個 <code>for</code> 迴圈逐一巡過目前英雄的超能力。針對每一項超能力,我們再建立 1 組 <code>&lt;li&gt;</code> 元素,把超能力放進該元素之中,再透過 <code>appendChild()</code> 把 <code>listItem</code> 放入 <code>&lt;ul&gt;</code> 元素之內 (<code>myList</code>)。</li>
+ <li>最後就是在 <code>&lt;article&gt;</code> (<code>myArticle</code>) 之內附加 <code>&lt;h2&gt;、</code><code>&lt;p&gt;、</code><code>&lt;ul&gt;</code>;再把 <code>&lt;article&gt;</code> 附加於 <code>&lt;section&gt;</code> 之內。這附加的順序極為重要,因為這也會是 HTML 中的顯示順序。</li>
+</ol>
+
+<div class="note">
+<p><strong>注意:</strong>如果你無法讓此範例運作,可參閱我們的 <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/heroes-finished.html">heroes-finished.html</a> 原始碼 (亦可看到<a href="http://mdn.github.io/learning-area/javascript/oojs/json/heroes-finished.html">實際執行情況</a>。)</p>
+</div>
+
+<div class="note">
+<p><strong>注意:</strong>如果你無法用我們說過的點記法 (dot-)\括弧記法 (bracket notation) 來存取 JSON,則可用新分頁或自己的文字編輯器開啟 <a href="http://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json">superheroes.json</a> 檔案並參考之。你也可再回去看看 <a href="/en-US/docs/Learn/JavaScript/Objects/Basics">JavaScript 物件基礎概念</a> ,再次了解點\括弧記法。</p>
+</div>
+
+<h2 id="物件與文字交互轉換">物件與文字交互轉換</h2>
+
+<p>上述是存取 JSON 的簡易範例,因為我們設定要回傳響應的 XHR 已經是 JSON 格式。透過:</p>
+
+<pre class="brush: js">request.responseType = 'json';</pre>
+
+<p>但有時候沒這麼好運。我們有時會接收到文字字串格式的 JSON 資料,且必須將之轉換為物件。且當我們要以某種訊息傳送 JSON 資料時,也必須將之轉換為字串才能正確運作。還好,這 2 種問題在 Web 開發過程中甚為常見。內建的 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON</a> 物件很早就新增到瀏覽器之中,且包含下列 2 種函式:</p>
+
+<ul>
+ <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse">parse()</a></code>:接收文字字串形式的 JSON 物件作為參數,並回傳對應的物件。</li>
+ <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">stringify()</a></code>:接收 JSON 物件作為參數,並回傳對等的文字字串形式。</li>
+</ul>
+
+<p>你可到 <a href="http://mdn.github.io/learning-area/javascript/oojs/json/heroes-finished-json-parse.html">heroes-finished-json-parse.html</a> 範例 (參閱<a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/heroes-finished-json-parse.html">原始碼</a>) 中看到第一個函式的運作情形。這其實跟我們先前範例所進行的事情一模一樣,不同之處在於我們設定 XHR 要回傳 JSON 為文字,接著再使用 <code>parse()</code> 轉換為實際的 JSON 物件。關鍵程式碼片段如下:</p>
+
+<pre class="brush: js">request.open('GET', requestURL);
+request.responseType = 'text'; // now we're getting a string!
+request.send();
+
+request.onload = function() {
+ var superHeroesText = request.response; // get the string from the response
+ var superHeroes = JSON.parse(superHeroesText); // convert it to an object
+ populateHeader(superHeroes);
+ showHeroes(superHeroes);
+}</pre>
+
+<p>你可能會猜 <code>stringify()</code> 就是反過來運作了吧?可在瀏覽器的 JavaScript 主控台上輸入下列程式碼,看看其運作方式:</p>
+
+<pre class="brush: js">var myJSON = { "name" : "Chris", "age" : "38" };
+myJSON
+var myString = JSON.stringify(myJSON);
+myString</pre>
+
+<p>這樣就建立了 JSON 物件了。接著檢查內容物之後,就可透過 <code>stringify()</code> 將之轉換為字串。將回傳值儲存到新變數之中,再檢查一次即可。</p>
+
+<h2 id="摘要">摘要</h2>
+
+<p>我們透過本文簡單介紹了該如何在程式中使用 JSON、該如何建立\剖析 JSON、該如何存取其內的資料。接著就要說明物件導向 JavaScript (OOJS)。</p>
+
+<h2 id="另可參閱">另可參閱</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON 物件參考頁面</a></li>
+ <li><a href="/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest 物件參考頁面</a></li>
+ <li><a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest">使用 XMLHttpRequest</a></li>
+ <li><a href="/en-US/docs/Web/HTTP/Methods">HTTP 請求函式</a></li>
+</ul>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects/Object_building_practice", "Learn/JavaScript/Objects")}}</p>
diff --git a/files/zh-tw/learn/javascript/objects/object-oriented_js/index.html b/files/zh-tw/learn/javascript/objects/object-oriented_js/index.html
new file mode 100644
index 0000000000..1504f5fc49
--- /dev/null
+++ b/files/zh-tw/learn/javascript/objects/object-oriented_js/index.html
@@ -0,0 +1,277 @@
+---
+title: 初學者應知道的物件導向 JavaScript
+slug: Learn/JavaScript/Objects/Object-oriented_JS
+translation_of: Learn/JavaScript/Objects/Object-oriented_JS
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects")}}</div>
+
+<p class="summary">在看完了基本概念之後,接著要說明物件導向 JavaScript (OOJS)。本文將概述物件導向程式設計 (OOP) 的理論,另說明 JavaScript 是如何透過建構子函式來模擬物件類別,又是如何建立物件實體 (Instance)。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">必備條件:</th>
+ <td>基本的電腦素養、已初步了解 HTML 與 CSS、熟悉 JavaScript (參閱〈<a href="/zh-TW/docs/Learn/JavaScript/First_steps">First steps</a>〉與〈<a href="/zh-TW/docs/Learn/JavaScript/Building_blocks">Building blocks</a>〉以及 OOJS 基礎概念 (參閱〈<a href="/zh-TW/docs/Learn/JavaScript/Object-oriented/Introduction">物件基礎概念</a>〉。</td>
+ </tr>
+ <tr>
+ <th scope="row">主旨:</th>
+ <td>了解物件導向程式設計的基本理論、其與 JavaScript (幾乎所有東西都是物件) 之間的關係、應如何寫出建構子與物件實體。</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="基本物件導向程式設計">基本物件導向程式設計</h2>
+
+<p>最先,讓我們從簡單、高層次的視角來看物件導向程式設計 (Object-oriented programming;OOP) 最基本的概念。我們說簡單是因為 OOP 很容易變得複雜,就算現在就設法完整解釋,也可能讓大家越來越混亂。OOP 基本概念是:採用物件(objects)來模塑真實的實物世界:也就是在程式中的呈現是透過 objects 來塑造其模型,且\或提供簡單方式存取其「難以或不可能採用的功能」。</p>
+
+<p>物件可裝載相關的資料與程式碼,資料部分是你塑造某個模型的資訊,而程式碼部分則用是操作行為(<strong>Method</strong>)實現。Object data  -- 函式部分通常也使用 ---可工整地儲存 (正式一點應該是<strong>封裝 Encapsulated</strong>) 在物件包裹(這個包裹有特定的稱呼方式,有時候即所謂的<strong>命名空間 Namespace</strong>) ,使其能輕鬆地建構性存取。物件也常作為「資料儲存 (Datastore),促成簡易實現跨網傳送。</p>
+
+<h3 id="定義物件範本">定義物件範本</h3>
+
+<p>我們先找個簡單程式,如同學校裡用來顯示師生資訊的程式。本文只是要了解一般的 OOP 理論,並非以特定程式語言為出發點。</p>
+
+<p>我們先拿<a href="/zh-TW/docs/Learn/JavaScript/Objects/Basics">第一篇物件文章</a>中的「Person」物件類型為範例,其中定義了一個人的一般資料與功能。其實有很多資訊可助你了解一個人 (像是住址、身高、鞋子尺寸、DNA、護照號碼、明顯的人格特質等......),但我們這裡只列出了姓名、年齡、性別、興趣。我們另希望根據這些資料寫出簡介,初步了解這個人。上述這些即所謂的「<strong>抽象 (Abstraction)」</strong>。為某個複雜東西建立簡單的模型,藉以代表其最重要的概念或特質,且該模型建立方式極易於搭配我們的程式設計用途。</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13889/person-diagram.png" style="display: block; height: 219px; margin: 0px auto; width: 610px;"></p>
+
+<h3 id="建立實際物件">建立實際物件</h3>
+
+<p>我們可從這個「類別」建立<strong>物件實體 (Object instance)</strong> — 即該物件包含了類別中所定義的資料與功能。而「Person」類別可設定出幾個實際的人物:</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13889/person-diagram.png" style="display: block; height: 219px; margin: 0px auto; width: 610px;"></p>
+
+<p>在根據類別建立物件實體時,就是執行類別的「<strong>建構子 (Constructor) 函式</strong>」所建立。而這個「根據類別來建立物件實體」的過程即稱為「<strong>實體化 (Instantiation)」</strong>。物件實體就是從類別實體化而來。</p>
+
+<h3 id="特殊類別">特殊類別</h3>
+
+<p>如果我們不要一般人物,而想建立老師與學生這類比較特定類型的人物。在 OOP 中,我們可根據其他類別建立新的類別。新的子類別則可<strong>繼承 (Inherit) </strong>其<strong>母類別</strong>的資料與程式碼特性。你可重複使用所有物件類型共有的功能,而不需再複製之。若功能需與類別有所差異,則可直接於其上定義特殊功能。</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13881/MDN-Graphics-inherited-3.png" style="display: block; height: 743px; margin: 0px auto; width: 700px;"></p>
+
+<p>這樣很方便。因為老師與學生也同樣使用了如姓名、性別、年齡等的共通特性,所以只要定義這些特性 1 次即可。你也可以分別在不同的類別中定義相同特性,各個特性的定義就置於不同的命名空間中。舉例來說,學生的打招呼方式可以是「Yo, I'm [firstName]」;老師的招呼方式就正式一點,如「Hello, my name is [Prefix] [lastName]」。</p>
+
+<div class="note">
+<p><strong>注意:</strong>所謂的<strong>「多型 (Polymorphism)」</strong>,即是用多個物件類別建置相同功能。</p>
+</div>
+
+<p>現在你可根據子類別來建立物件實例了。例如:</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13885/MDN-Graphics-instantiation-teacher-3.png" style="display: block; height: 743px; margin: 0px auto; width: 700px;"></p>
+
+<p>本文後面將講解應如何將 OOP 理論實際用於 JavaScript 中。</p>
+
+<h2 id="建構子與物件實例">建構子與物件實例</h2>
+
+<p>JavaScript 使用稱為建構子函式(<strong>constructor function</strong>)的特殊函式,定義物件與功能。開發者常常會不知道到底需建立多少物件,這時建構子可讓你高效率建立所需物件,並依需要為其添加資料與函式。</p>
+
+<p>在新的物件實例透過建構子函式產生後,其核心將透過一種稱為<strong>原型鏈</strong>(Prototype chain,由原型定義,可參閱 <a href="/zh-TW/docs/Learn/JavaScript/Objects/Object_prototypes">Object prototypes</a>)的參照鏈連在一起。</p>
+
+<p>接著就在 JS 中,透過建構子建立類別及其物件實例。首先請你先在本端磁碟中再另外複製一份前面文章提過的 <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/introduction/oojs.html">oojs.html</a> 檔案。</p>
+
+<h3 id="簡易範例">簡易範例</h3>
+
+<ol>
+ <li>先看看該如何用一般函式定義一個人。將下列函式加到 <code>script</code> 元素裡面:
+
+ <pre class="brush: js">function createNewPerson(name) {
+ var obj = {};
+ obj.name = name;
+ obj.greeting = function () {
+ alert('Hi! I\'m ' + this.name + '.');
+ }
+ return obj;
+}</pre>
+ </li>
+ <li>呼叫此函式之後即可建立新的 1 個人,另在瀏覽器的 JavaScript 主控台中測試下列程式碼:
+ <pre class="brush: js">var salva = createNewPerson('salva');
+salva.name;
+salva.greeting();</pre>
+ 目前為止沒什麼問題,但有點囉嗦。如果早知道要建立物件的話,又何必要建立新的空白物件再回傳呢?幸好 JavaScript 透過建構子函式提供了方便的捷徑。現在就來試試看!</li>
+ <li>用下列程式碼替代之前的函式:
+ <pre class="brush: js">function Person(name) {
+ this.name = name;
+ this.greeting = function() {
+ alert('Hi! I\'m ' + this.name + '.');
+ };
+}</pre>
+ </li>
+</ol>
+
+<p>建構子也就是 JavaScript 版本的「類別」之一。你可以注意到,除了無法回傳任何數值或明確建立物件之外,建構子其實已具備函式中的所有功能,並已基本定義了屬性與函式 (Method)。你也能看到這裡同樣用了「<code>this</code>」關鍵字,即不論何時建立了這裡的任一物件實例,物件的「<code>name</code>」屬性均同等於「傳送至建構子呼叫的名稱值」;且 <code>greeting()</code> 函式也會使用相同「傳送至建構子呼叫的名稱值」。</p>
+
+<div class="note">
+<p><strong>注意:</strong>建構子函式名稱往往以大寫字母起頭,如此可方便你在程式碼中找出建構子函式。</p>
+</div>
+
+<p>我們又該如何呼叫建構子以建立物件呢?</p>
+
+<ol>
+ <li>將下列程式碼加到目前的程式碼之下:
+ <pre class="brush: js">var person1 = new Person('Bob');
+var person2 = new Person('Sarah');</pre>
+ </li>
+ <li>儲存程式碼並在瀏覽器中重新載入,試著將下列程式碼輸入到文字輸入畫面中:
+ <pre class="brush: js">person1.name
+person1.greeting()
+person2.name
+person2.greeting()</pre>
+ </li>
+</ol>
+
+<p>現在你應該能在頁面上看到兩組新物件,且各自以不同的命名空間儲存。若要存取其屬性與函式,就要以 <code>person1</code> 或 <code>person2</code> 開始呼叫。這些物件均完整封包,不致與其他功能衝突;但仍具備相同的 <code>name</code> 屬性與 <code>greeting()</code> 函式。另請注意,物件均使用當初建立時所各自指派的 <code>name</code> 值;這也是「<code>this</code>」如此重要的原因之一,以確保物件可使用自己的值而不致混淆其他數值。</p>
+
+<p>再看一次建構子呼叫:</p>
+
+<pre class="brush: js">var person1 = new Person('Bob');
+var person2 = new Person('Sarah');</pre>
+
+<p>這裡用了「<code>new</code>」關鍵字告知瀏覽器「我們要建立新的物件實例」,並接著在函式名稱之後的括號內傳入函式所需要的參數,並將結果儲存於變數之中 — 相當類似普通函式被呼叫的方式 。各個實例均根據此定義所建立:</p>
+
+<pre class="brush: js">function Person(name) {
+ this.name = name;
+ this.greeting = function() {
+ alert('Hi! I\'m ' + this.name + '.');
+ };
+}</pre>
+
+<p>在建立新的物件之後,<code>person1</code> 與 <code>person2</code> 的變數將有效率地納入下列物件:</p>
+
+<pre class="brush: js">{
+ name : 'Bob',
+ greeting : function() {
+ alert('Hi! I\'m ' + this.name + '.');
+ }
+}
+
+{
+ name : 'Sarah',
+ greeting : function() {
+ alert('Hi! I\'m ' + this.name + '.');
+ }
+}</pre>
+
+<p>剛剛說的「有效率」,是因為實際功能仍定義於類別中,而非物件實例之中。這情況與我們稍早談過的物件實字 (Object literal) 相反。</p>
+
+<h3 id="建立完整的建構子">建立完整的建構子</h3>
+
+<p>上面不過是入門的簡單範例。接著繼續建立最後的 <code>Person()</code> 建構子。</p>
+
+<ol>
+ <li>將截至目前為止的程式碼移除,加入下列取代用的建構子。原則上與簡易範例完全一樣,只是比較複雜一點:
+ <pre class="brush: js">function Person(first, last, age, gender, interests) {
+ this.name = {
+ first,
+ last
+ };
+ this.age = age;
+ this.gender = gender;
+ this.interests = interests;
+ this.bio = function() {
+ alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
+ };
+ this.greeting = function() {
+ alert('Hi! I\'m ' + this.name.first + '.');
+ };
+};</pre>
+ </li>
+ <li>再接著加入下列程式碼,就可建立物件實例:
+ <pre class="brush: js">var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);</pre>
+ </li>
+</ol>
+
+<p>現在可存取我們為第一個物件所定義的屬性與函式:</p>
+
+<pre class="brush: js">person1['age']
+person1.interests[1]
+person1.bio()
+// etc.</pre>
+
+<div class="note">
+<p><strong>注意:</strong>如果你到這裡有點吃力,請先比較自己與我們的程式碼。可參閱 <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/introduction/oojs-class-finished.html">oojs-class-finished.html</a> (也可<a href="http://mdn.github.io/learning-area/javascript/oojs/introduction/oojs-class-finished.html">看實際執行的情況</a>)。</p>
+</div>
+
+<h3 id="進階習題">進階習題</h3>
+
+<p>在開始之前,先試著自己添加更多物件建立程式碼,再針對產生的物件實例取得並設定其成員。</p>
+
+<p>此外,原來的 <code>bio()</code> 函式其實有點問題。即使你的「人」是女性,其輸出一定會有「He」這個代名詞。而且即使 <code>interests</code> 陣列中列出超過 2 個以上的「興趣」,這個 bio 函式也只會有 2 個興趣。你能試著在類別定義 (建構子) 中修正這個問題嗎?你可在建構子中放入任何你喜歡的程式碼 (但可能會需要幾個 conditionals 搭配 1 個迴圈)。想想應如何根據性別以及列出的興趣 (1 或 2 個以上),建構出不同的程式碼。</p>
+
+<div class="note">
+<p><strong>注意:</strong>如果你卡在這裡,我們也在 <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/introduction/oojs-class-further-exercises.html">GitHub repo 上提供了解答</a> (<a href="http://mdn.github.io/learning-area/javascript/oojs/introduction/oojs-class-further-exercises.html">立刻觀看</a>)。先試著自己解決問題吧!</p>
+</div>
+
+<h2 id="建立物件實例的其他方法">建立物件實例的其他方法</h2>
+
+<p>目前解釋了 2 種建立物件實例的方法 — <a href="/zh-TW/docs/Learn/JavaScript/Objects/Basics#Object_basics">宣告物件實字</a>,以及使用建構子函式。</p>
+
+<p>當然還有別的方法,但我們希望你先熟悉此 2 種方法,以免你日後的 Web 旅程上會再遇到。</p>
+
+<h3 id="Object_建構子">Object() 建構子</h3>
+
+<p>首先可使用 <code><a href="/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object">Object()</a></code> 建構子建立新的物件。沒錯,即使是泛型物件 (Generic object) 也具備建構子,可用以產生空白物件。</p>
+
+<ol>
+ <li>將下列輸入瀏覽器的 JavaScript 主控台內:
+ <pre class="brush: js">var person1 = new Object();</pre>
+ </li>
+ <li>如此會在 <code>person1</code> 變數中儲存 1 組空白物件。接著可透過點 (dot-) 或括弧記法 (bracket notation) 為此物件新增屬性與函式。如下列範例:
+ <pre class="brush: js">person1.name = 'Chris';
+person1['age'] = 38;
+person1.greeting = function() {
+ alert('Hi! I\'m ' + this.name + '.');
+}</pre>
+ </li>
+ <li>你可將一組物件實字傳送給 <code>Object()</code> 建構子作為參數,藉以預先填入屬性\函式。如下所示:
+ <pre class="brush: js">var person1 = new Object({
+ name : 'Chris',
+ age : 38,
+ greeting : function() {
+ alert('Hi! I\'m ' + this.name + '.');
+ }
+});</pre>
+ </li>
+</ol>
+
+<h3 id="使用_create_函式">使用 create() 函式</h3>
+
+<p>建構子可以幫助你保持程式的可讀性 — 你可以將建構子建立在同一個地方,並根據需求從這些建構子中建立物件實例,這樣做可以讓你清楚地得知它們的來源。</p>
+
+<p>不過,有些人偏好建立物件實例,而不先做建構子,尤其是他們的物件不會用很多實例時。JavaScript 有個稱作 <code><a href="/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/create">create()</a></code> 的內建函式能讓你這麼做。有了它,你就能根據現有物件,建立新的物件。</p>
+
+<ol>
+ <li>在 JavaScript 主控台裡測試:
+ <pre class="brush: js">var person2 = Object.create(person1);</pre>
+ </li>
+ <li>再測試以下:
+ <pre class="brush: js">person2.name
+person2.greeting()</pre>
+ </li>
+</ol>
+
+<p>你會看到 <code>person2</code> 是根據 <code>person1</code> 所建立:它具備了相同的屬性以及可用的函式。</p>
+
+<p><code>create()</code> 的其中一個限制,就是 IE8 並不支援。因此,如果你需要支援舊版瀏覽器,建構子會比較有用。</p>
+
+<p>我們後續會再說明 <code>create()</code> 的效果。</p>
+
+<h2 id="總結">總結</h2>
+
+<p>本文簡略說明了 OO 理論,雖然還沒全部講完,至少也讓你初步了解到本文所要闡述的重點。此外,我們已經開始說明 JavaScript 與 OO 之間的關係、其與「傳統 OO」之間的差異、使用建構子於 JavaScript 中實作類別的方法,以及其他產生物件實例的方式。</p>
+
+<p>下一篇文章將說明 JavaScript 物件原型。</p>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects")}}</p>
+
+<h2 id="In_this_module">In this module</h2>
+
+<ul>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/Objects/Basics">Object basics</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/Objects/Object-oriented_JS">Object-oriented JavaScript for beginners</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/Objects/Object_prototypes">Object prototypes</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/Objects/Inheritance">Inheritance in JavaScript</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/Objects/JSON">Working with JSON data</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/Objects/Object_building_practice">Object building practice</a></li>
+ <li><a href="/zh-TW/docs/Learn/JavaScript/Objects/Adding_bouncing_balls_features">Adding features to our bouncing balls demo</a></li>
+</ul>
diff --git a/files/zh-tw/learn/javascript/objects/object_building_practice/index.html b/files/zh-tw/learn/javascript/objects/object_building_practice/index.html
new file mode 100644
index 0000000000..4a47aa39eb
--- /dev/null
+++ b/files/zh-tw/learn/javascript/objects/object_building_practice/index.html
@@ -0,0 +1,283 @@
+---
+title: 物件建構實作
+slug: Learn/JavaScript/Objects/Object_building_practice
+tags:
+ - Canvas
+ - JavaScript
+translation_of: Learn/JavaScript/Objects/Object_building_practice
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects/Adding_bouncing_balls_features", "Learn/JavaScript/Objects")}}</div>
+
+<p class="summary">我們解說完必要的 JavaScript 物件理論以及語法細節,想先幫你把根紮好。接著就透過實作範例,讓你實際建立自己有趣又多彩的 JavaScript 物件。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">必備條件:</th>
+ <td>基礎的計算機素養、了解 HTML 與 CSS 的基本概念、熟悉 JavaScript (參閱〈<a href="/en-US/docs/Learn/JavaScript/First_steps">First steps</a>〉與〈<a href="/en-US/docs/Learn/JavaScript/Building_blocks">Building blocks</a>〉) 與 OOJS 基本概念 (參閱〈<a href="/en-US/docs/Learn/JavaScript/Object-oriented/Introduction">Introduction to objects</a>〉)。</td>
+ </tr>
+ <tr>
+ <th scope="row">要點:</th>
+ <td>親手實作物件與物件導向 (OO) 技術。</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="弄一些彈跳彩球">弄一些彈跳彩球</h2>
+
+<p>本文將帶領你實作經典的「彈跳球」展示網頁,讓你了解物件在 JavaScript 中的用處。這些小球會在畫面上四處彈跳,而且互相碰撞時變換顏色。範例成品如下:</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13865/bouncing-balls.png" style="display: block; height: 614px; margin: 0px auto; width: 800px;"></p>
+
+<ol>
+</ol>
+
+<p>此範例將透過 <a href="/en-US/docs/Web/API/Canvas_API">Canvas API</a> 在畫面上繪製球體,<a href="/en-US/docs/Web/API/window/requestAnimationFrame">requestAnimationFrame</a> API 則是繪製整個動畫;而且你不需先了解此兩個 API。但我們希望在看完本文之後,能引起大家深入探究此兩個 API 的興趣。整個過程會利用某些花俏的物件,並讓你看到幾項有趣技術,像是球體從牆上回彈,並檢查球體是否互相碰撞 (也就是碰撞偵測)。</p>
+
+<h2 id="著手開始">著手開始</h2>
+
+<p>先複製 <code><a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/bouncing-balls/index.html">index.html</a></code><code>、<a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/bouncing-balls/style.css">style.css</a></code>、<code><a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/bouncing-balls/main.js">main.js</a></code> 檔案到你的本機磁碟中。這些檔案分別具備下列:</p>
+
+<ol>
+ <li>極簡的 HTML 文件,具備 1 個 {{HTMLElement("h1")}} 元素、1 個 {{HTMLElement("canvas")}} 元素可繪製彩球,以及其他元素可將 CSS 與 JavaScript 套用到 HTML 之上。</li>
+ <li>一些極簡單的樣式,主要可作為 <code>&lt;h1&gt; 的樣式風格與定位之用,並省去網頁邊緣的捲動棒或空白</code> (看起來更簡約)。</li>
+ <li>某些 JavaScript 可用以設定 <code>&lt;canvas&gt;</code> 元素,另有通用函式可供我們往後使用。</li>
+</ol>
+
+<p>指令碼第一部分就像:</p>
+
+<pre class="brush: js">var canvas = document.querySelector('canvas');
+
+var ctx = canvas.getContext('2d');
+
+var width = canvas.width = window.innerWidth;
+var height = canvas.height = window.innerHeight;</pre>
+
+<p>此指令碼將為 <code>&lt;canvas&gt;</code> 元素提供參照,接著於其上呼叫 <code><a href="/en-US/docs/Web/API/HTMLCanvasElement/getContext">getContext()</a></code> 函式,藉以提供能開始繪圖的內文 (Context)。所產生的變數 (<code>ctx</code>) 也就是物件,將直接呈現 canvas 的繪圖區域,讓我們繪製 2D 圖像。</p>
+
+<p>接著設定 <code>width</code> 與 <code>height</code> 共 2 個變數,也就是 canvas 元素的寬度與高度 (透過 <code>canvas.width</code> 與 <code>canvas.height</code> 屬性呈現) 即等於瀏覽器可視區的寬度與高度 (也就是網頁顯示的區域 — 可經由 {{domxref("Window.innerWidth")}} 與 {{domxref("Window.innerHeight")}} 屬性得知)。</p>
+
+<p>你會看到我們在這裡串連了多個指定式,以快速設定所有變數,而且運作無虞。</p>
+
+<p>剛開始的指令碼後半部如下:</p>
+
+<pre class="brush: js">function random(min, max) {
+ var num = Math.floor(Math.random()*(max-min)) + min;
+ return num;
+}</pre>
+
+<p>此函式共有 2 組參數 (argument),並會回傳此範圍之內的任意值。</p>
+
+<h2 id="在程式中設定球體的模型">在程式中設定球體的模型</h2>
+
+<p>我們的程式會讓一堆彩球在畫面中彈來彈去。因為這些球體的行動方式均相同,所以透過物件呈現這些彩球也合情合理。先在程式碼底部加入下列建構子:</p>
+
+<pre class="brush: js">function Ball() {
+ this.x = random(0,width);
+ this.y = random(0,height);
+ this.velX = random(-7,7);
+ this.velY = random(-7,7);
+ this.color = 'rgb(' + random(0,255) + ',' + random(0,255) + ',' + random(0,255) +')';
+ this.size = random(10,20);
+}</pre>
+
+<p>這裡我們要定義某些屬性,以利彩球能在程式中動作:</p>
+
+<ul>
+ <li><code>x</code> 與 <code>y</code> 座標 — 每顆彩球都會先有位於畫面中的隨機水平\垂直座標。範圍從 0 (最左上角) 到瀏覽器可視區的寬\高度 (最右下角) 為止。</li>
+ <li>水平與垂直速度 (<code>velX</code> 與 <code>velY</code>) — 每顆彩球均具備隨機的速度值;在我們開始彩球動畫時,這些數值就會加上 <code>x</code>/<code>y</code> 座標值,以利在各畫格(frame)中移動彩球。</li>
+ <li><code>color</code> — 彩球的顏色是隨機產生。</li>
+ <li><code>size</code> — 各彩球大小亦為隨機,從 10 到 20 像素不等。</li>
+</ul>
+
+<p>屬性講完了,那函式呢?程式中的彩球要實際運作才行。</p>
+
+<h3 id="繪製球體">繪製球體</h3>
+
+<p>先將下列 <code>draw()</code> 函式加到 <code>Ball() 的</code> <code>prototype 之中:</code></p>
+
+<pre class="brush: js">Ball.prototype.draw = function() {
+ ctx.beginPath();
+ ctx.fillStyle = this.color;
+ ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
+ ctx.fill();
+}</pre>
+
+<p>透過此函式,再呼叫我們之前定義在 2D canvas 內文(ctx)中的物件成員,就能讓球體自己在螢幕上畫出自己。此內文就像是白紙一樣,接著就用筆在紙上畫出點東西:</p>
+
+<ul>
+ <li>首先以 <code><a href="/en-US/docs/Web/API/CanvasRenderingContext2D/beginPath">beginPath()</a></code> 聲明我們要在紙上畫出來的形狀。</li>
+ <li>接著用 <code><a href="/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle">fillStyle</a></code> 定義該形狀所要呈現的顏色 — 設定為球體的 <code>color</code> 屬性。</li>
+ <li>再用 <code><a href="/en-US/docs/Web/API/CanvasRenderingContext2D/arc">arc()</a></code> 函式在紙上勾勒出弧形。相關參數為:
+ <ul>
+ <li>弧形中心的 <code>x</code> 與 <code>y</code> 位置 — 我們指定球體的 <code>x</code> 與 <code>y</code> 屬性。</li>
+ <li>弧形半徑 — 指定球體的 <code>size</code> 屬性。</li>
+ <li>最後 2 項參數則指定弧形繪製時的圓圈起、終點角度。我們這裡指定 0 度與 <code>2 * PI</code> 度,這也等於半徑繞了 360 度 (你必須在半徑中指定,有點煩)。如此構成完整的圓。如果你只設定了 <code>1 * PI,就會只有半球體</code> (即 180 度)。</li>
+ </ul>
+ </li>
+ <li>最後使用 <code><a href="/en-US/docs/Web/API/CanvasRenderingContext2D/fill">fill()</a></code> 函式,基本上是用來聲稱「完成我們以 <code>beginPath()</code> 開始的繪圖路徑,再用 <code>fillStyle 中指定的色彩將之填滿</code>」。</li>
+</ul>
+
+<p>你已經可以開始測試自己的物件了。</p>
+
+<ol>
+ <li>儲存目前的程式碼,在瀏覽器中載入此 HTML 檔案。</li>
+ <li>開啟瀏覽器的 JavaScript 主控台,並在主控台開啟時重新整理網頁,讓 canvas 尺寸變更為左側較小型的可視區域。</li>
+ <li>鍵入下列程式碼以建立新的球體實例:
+ <pre class="brush: js">var testBall = new Ball();</pre>
+ </li>
+ <li>再呼叫其成員:
+ <pre class="brush: js">testBall.x
+testBall.size
+testBall.color
+testBall.draw()</pre>
+ </li>
+ <li>輸入最後一行之後,應該就能看到 canvas 上出現自己產生的球體。</li>
+</ol>
+
+<h3 id="更新球體的資料">更新球體的資料</h3>
+
+<p>現在可以繪製彩球了。但在讓球彈跳之前,我們必須先更新幾個函式。將下列程式碼加到 JavaScript 檔案底端,把 <code>update()</code> 函式加到 <code>Ball()</code> 的 <code>prototype</code> 之中:</p>
+
+<pre class="brush: js">Ball.prototype.update = function() {
+ if((this.x + this.size) &gt;= width) {
+ this.velX = -(this.velX);
+ }
+
+ if((this.x - this.size) &lt;= 0) {
+ this.velX = -(this.velX);
+ }
+
+ if((this.y + this.size) &gt;= height) {
+ this.velY = -(this.velY);
+ }
+
+ if((this.y - this.size) &lt;= 0) {
+ this.velY = -(this.velY);
+ }
+
+ this.x += this.velX;
+ this.y += this.velY;
+}</pre>
+
+<p>函式的前 4 個部分負責檢查球體是否碰到 canvas 邊緣。如果球體抵達邊緣,我們就反轉相對加速度的方向,讓球反方向行進。以球體向上 (正向 <code>velX</code>) 時為例,接著就會改變水平速度,球體也就反向運動。</p>
+
+<p>在這 4 個情境中,我們:</p>
+
+<ul>
+ <li>檢查 <code>x</code> 座標是否大於 canvas 的寬度 (球體抵達右側邊緣)。</li>
+ <li>檢查 <code>x</code> 座標是否小於 0 (球體抵達左側邊緣)。</li>
+ <li>檢查 <code>y</code> 座標是否大於 canvas 的高度 (球體抵達底部邊緣)。</li>
+ <li>檢查 <code>y</code> 座標是否小於 0 (球體抵達頂部邊緣)。</li>
+</ul>
+
+<p>在各情境中,因為 <code>x</code>/<code>y</code> 座標為球體的中心,所以我們把球體的 <code>size</code> 納入計算,但我們不要球體在回彈之前在半路上就跳出畫面之外。</p>
+
+<p>最後 2 行則是將 <code>velX</code> 與 <code>velY</code> 值分別加入 <code>x\y</code> 座標之中;每次只要呼叫此函式,球體就會依照應有的效果移動。</p>
+
+<p>到這裡沒有問題的話,就開始弄動畫吧!</p>
+
+<h2 id="球體動起來">球體動起來</h2>
+
+<p>接著來玩玩吧。我們要加更多球到 canvas 中並開始動畫效果。</p>
+
+<ol>
+ <li>首先要弄個地方儲存所有的彩球。將下方陣列加到現有程式碼底部即可:
+ <pre class="brush: js">var balls = [];</pre>
+
+ <p>所有可提供動畫效果的程式,一般都會採用動畫迴圈,可用以更新程式中的資訊,並接著在動畫的各個畫格上繪製產生的結果。這也是大部分遊戲或類似程式的基礎。</p>
+ </li>
+ <li>再將下列程式碼加到現有程式碼底部:
+ <pre class="brush: js">function loop() {
+ ctx.fillStyle = 'rgba(0,0,0,0.25)';
+ ctx.fillRect(0,0,width,height);
+
+ while(balls.length &lt; 25) {
+ var ball = new Ball();
+ balls.push(ball);
+ }
+
+ for(i = 0; i &lt; balls.length; i++) {
+ balls[i].draw();
+ balls[i].update();
+ }
+
+ requestAnimationFrame(loop);
+}</pre>
+
+ <p>我們的 <code>loop()</code> 函式可進行:</p>
+
+ <ul>
+ <li>設定 canvas 填滿色彩或是半透明的黑色。接著透<code>過 fillRect()</code> (共 4 個參數提供起始座標,以及繪製矩形的高度與寬度),跨 canvas 的寬度與高度繪製整個矩型的色彩。如此可在繪製下一個畫格之前,先覆蓋前一個已存在的畫格;否則會看到許多隻長長的蛇爬來爬去。填充顏色已設定為半透明狀態:<code>rgba(0,0,0,0.25)</code> 可讓先前的畫格微微發亮,製造出球體移動時的小尾巴效果。如果將 0.25 更改為 1,就會完全消除尾巴。你可自己測試不同的數值,找出自己喜歡的效果。</li>
+ <li>可對 <code>Ball()</code> 建立新的實作,接著將之 <code>push()</code> 到球體陣列的最後,且彩球數量必須少於 25 個。所以整個畫面最多顯示 25 個球。你可嘗試變更 <code>balls.length &lt; 25</code> 中的數值,畫面中的彩球數量也會隨著變化。依你所用電腦\瀏覽器處理效能的不同,若繪製上千個彩球就會拖慢整個動畫的速度。</li>
+ <li>迴圈將巡過 <code>balls</code> 陣列中的所有彩球,並執行各個彩球的 <code>draw()</code> 與 <code>update()</code> 函式,以於畫面中逐一繪製,接著對下個畫格的位置與速度執行必要更新。</li>
+ <li>再以 <code>requestAnimationFrame()</code> 函式執行過此函式 — 當此函式持續執行並傳送相同的函式名稱時,就會每秒執行此函式達特定次數,以產生流暢的動畫。接著重複執行此作業,也就是函式每次執行時均會呼叫自身 1 次,進而循環執行。</li>
+ </ul>
+ </li>
+ <li>最後將下列程式碼加入最底端,呼叫函式 1 次讓動畫開始運作。
+ <pre class="brush: js">loop();</pre>
+ </li>
+</ol>
+
+<p>基本就是這樣了。試著儲存並重新整理檔案,讓你的彩球開始跳動吧!</p>
+
+<h2 id="另增碰撞偵測">另增碰撞偵測</h2>
+
+<p>現在弄點有趣的東西,就把碰撞偵測 (Collision detection) 加進程式裡,讓彩球知道自己碰到其他球了。</p>
+
+<ol>
+ <li>首先將下列函式定義加進你自己定義 <code>update()</code> 函式中 (例如 <code>Ball.prototype.update</code> 區塊):
+
+ <pre class="brush: js">Ball.prototype.collisionDetect = function() {
+ for(j = 0; j &lt; balls.length; j++) {
+ if( (!(this.x === balls[j].x &amp;&amp; this.y === balls[j].y &amp;&amp; this.velX === balls[j].velX &amp;&amp; this.velY === balls[j].velY)) ) {
+ var dx = this.x - balls[j].x;
+ var dy = this.y - balls[j].y;
+ var distance = Math.sqrt(dx * dx + dy * dy);
+
+ if (distance &lt; this.size + balls[j].size) {
+ balls[j].color = this.color = 'rgb(' + random(0,255) + ',' + random(0,255) + ',' + random(0,255) +')';
+ }
+ }
+ }
+}</pre>
+
+ <p>這函式有點複雜,所以現在不瞭解如何運作的也別擔心。解釋如下:</p>
+
+ <ul>
+ <li>對每個彩球來說,我們必須檢查是否碰撞到其他球。所以要設定另一個 <code>for</code> 迴圈以循環檢視 <code>balls[]</code> 陣列中的所有彩球。</li>
+ <li>在我們的 for 迴圈中,我們立刻使用 <code>if</code> 陳述式檢查「現正透過迴圈循環檢查中」的彩球,是否即為我們目前檢查中的同一彩球。我們不需要檢查彩球是否碰撞到自己!為了達到此效果,我們檢查彩球目前的 <code>x</code>/<code>y</code> 座標與速度,是否等同於迴圈檢查的彩球。接著透過「<code>!</code>」否定檢查,所以在 if 陳述式中的程式碼,只有在彩球相異時才會執行。</li>
+ <li>接著使用一般演算法檢查 2 個球體之間的碰撞。我們基本上會檢查任 2 個球體的範圍是否重疊。另將透過〈<a href="/en-US/docs/Games/Techniques/2D_collision_detection">2D 碰撞偵測</a>〉一文進一步解釋。</li>
+ <li>如果偵測到碰撞,則隨即執行內部 <code>if</code> 陳述式的程式碼。在本範例中,我們剛設定了 2 個球體的 <code>color</code> 屬性為新的隨機色彩。但當然可以更複雜點,像是讓彩球更逼真的互相反彈,但這實作起來就更複雜了。對這類的物理模擬,開發者就必須使用如 <a href="http://wellcaffeinated.net/PhysicsJS/">PhysicsJS</a>、<a href="http://brm.io/matter-js/">matter.js</a>、<a href="http://phaser.io/">Phaser</a> 等的遊戲\物理函式庫。</li>
+ </ul>
+ </li>
+ <li>你也可以在動畫的每一畫格中呼叫此一函式。在 <code>balls[i].update();</code> 這一行下方新增下列程式碼即可:
+ <pre class="brush: js">balls[i].collisionDetect();</pre>
+ </li>
+ <li>儲存並重新整理之後,就能看到球體在碰撞時變更其色彩了!</li>
+</ol>
+
+<div class="note">
+<p><strong>注意:</strong>如果你無法讓此範例順利運作,可比較我們的<a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/bouncing-balls/main-finished.js">最後版本</a> (另可參閱<a href="http://mdn.github.io/learning-area/javascript/oojs/bouncing-balls/index-finished.html">實際執行情形</a>)。</p>
+</div>
+
+<h2 id="摘要">摘要</h2>
+
+<p>希望你喜歡撰寫出隨機彩球碰撞範例,其內並包含我們前面說過的多樣物件與 OO 技術!本文應該已提供你有用的物件實作與絕佳的實際文本。</p>
+
+<p>物件實體就到這裡。接著就是你要磨練自己的物件技術了!</p>
+
+<h2 id="另可參閱">另可參閱</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial">Canvas 線上教學</a> — 2D canvas 初學者指南</li>
+ <li><a href="/en-US/docs/Web/API/window/requestAnimationFrame">requestAnimationFrame()</a></li>
+ <li><a href="/en-US/docs/Games/Techniques/2D_collision_detection">2D 碰撞偵測</a></li>
+ <li><a href="/en-US/docs/Games/Techniques/3D_collision_detection">3D 碰撞偵測</a></li>
+ <li><a href="/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript">只使用 JavaScript 的 2D 打磚塊遊戲</a> — 2D 遊戲開發初學者的絕佳線上教學</li>
+ <li><a href="/en-US/docs/Games/Tutorials/2D_breakout_game_Phaser">剖析器 (Phaser) 的 2D 打磚塊遊戲</a> — 以 JavaScript 遊戲函式庫建構 2D 遊戲的基本概念</li>
+</ul>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects/Adding_bouncing_balls_features", "Learn/JavaScript/Objects")}}</p>
diff --git a/files/zh-tw/learn/javascript/objects/object_prototypes/index.html b/files/zh-tw/learn/javascript/objects/object_prototypes/index.html
new file mode 100644
index 0000000000..9bfbc98fea
--- /dev/null
+++ b/files/zh-tw/learn/javascript/objects/object_prototypes/index.html
@@ -0,0 +1,236 @@
+---
+title: 物件原型
+slug: Learn/JavaScript/Objects/Object_prototypes
+translation_of: Learn/JavaScript/Objects/Object_prototypes
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects")}}</div>
+
+<p class="summary">JavaScript 的物件即透過原型 (Prototype) 機制相互繼承功能,且與典型的物件導向 (OO) 程式語言相較,其運作方式有所差異。我們將透過本文說明相異之處、解釋原型鍊 (Prototype chain) 運作的方式,並了解原型屬性是如何將函式新增至現有的建構子 (Constructor) 之中。</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">必備條件:</th>
+ <td>基本的電腦素養、已初步了解 HTML 與 CSS、熟悉 JavaScript (參閱〈<a href="/en-US/docs/Learn/JavaScript/First_steps">First steps</a>〉與〈<a href="/en-US/docs/Learn/JavaScript/Building_blocks">Building blocks</a>〉以及 OOJS 基礎概念 (參閱〈<a href="/en-US/docs/Learn/JavaScript/Object-oriented/Introduction">Introduction to objects</a>〉。</td>
+ </tr>
+ <tr>
+ <th scope="row">主旨:</th>
+ <td>了解 JavaScript 的物件原型、原型鍊的運作方式、應如何將新的函式加入原型屬性之中。</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="「原型」架構的程式語言?">「原型」架構的程式語言?</h2>
+
+<p>常有人說 JavaScript 是<strong>原型架構的程式語言 </strong>— 各個物件均具備 1 組<strong>原型物件</strong>作為範本物件,用以繼承函式與屬性。物件的原型物件可能也具備原型物件,並繼承了其上的函式與屬性。這就是我們所謂的「<strong>原型鍊 (Prototype chain)</strong>」,同時正好說明為何 A 物件的屬性與函式是透過 B 物件的屬性與函式所定義。</p>
+
+<p>精確點說,這些屬性與函式都是透過物件的建構子函式所定義,並非物件實例本身。</p>
+
+<p>傳統的 OOP 都是先定義了類別,接著在建立物件實例之後,在類型上定義的所有屬性與函式均複製到此實例。但 JavaScript 不會複製這些屬性與函式,卻是在物件實例與其建構子之間設定連結 (原型鍊中的連結),只要順著原型鍊就能在建構子之中找到屬性與函式。</p>
+
+<p>先看個範例會比較清楚點。</p>
+
+<h2 id="了解原型物件">了解原型物件</h2>
+
+<p>先回到我們寫過的 <code>Person()</code> 建構子範例。在你的瀏覽器裡載入範例。如果你還沒看完前篇文章並製作出此範例,可先使用 <a href="http://mdn.github.io/learning-area/javascript/oojs/introduction/oojs-class-further-exercises.html">oojs-class-further-exercises.html</a> 這個範例 (可看到<a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/introduction/oojs-class-further-exercises.html">原始碼</a>)。</p>
+
+<p>我們在此範例中定義了建構子函式:</p>
+
+<pre class="brush: js">function Person(first, last, age, gender, interests) {
+
+ // property and method definitions
+
+};</pre>
+
+<p>接著建立如下的物件實例:</p>
+
+<pre class="brush: js">var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);</pre>
+
+<p>如果你在自己的 JavaScript 主控台中鍵入「<code>person1.」,應該會看到瀏覽器根據此物件可用的成員名稱開始自動補完:</code></p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13853/object-available-members.png" style="display: block; margin: 0 auto;"></p>
+
+<p>在此列表中,可以看到 <code>person1</code> 原型物件上所定義的成員,也就是 <code>Person()</code> 建構子 — <code>name</code>、<code>age</code>、<code>gender</code>、<code>interests</code>、<code>bio</code>、<code>greeting</code>。你也會看到其他如 <code>watch</code>、<code>valueOf 等,同樣也是定義在</code> <code>Person()</code> 建構子原型物件之上的成員,如此構成 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a></code>。下圖顯示原型鍊的運作方式。</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13891/MDN-Graphics-person-person-object-2.png" style="display: block; height: 150px; margin: 0px auto; width: 700px;"></p>
+
+<p>所以當你在 <code>person1 上呼叫了「實際上是定義於 Object 上的函式」,會發生什麼事呢?舉例來說:</code></p>
+
+<pre class="brush: js">person1.valueOf()</pre>
+
+<p>此函式僅回傳所呼叫的物件數值。此範例所將發生的是:</p>
+
+<ul>
+ <li>瀏覽器先檢查 <code>person1</code> 物件上是否有可用的 <code>valueOf()</code> 函式。</li>
+ <li>其實沒有,所以瀏覽器接著檢查 <code>person1</code> 物件的原型物件 (<code>Person</code>) 上是否有可用的 <code>valueOf()</code> 函式。</li>
+ <li>同樣沒有,所以瀏覽器再檢查 <code>Person()</code> 建構子的原型物件 (<code>Object</code>) 上是否有可用的 <code>valueOf()</code> 函式。這次有,所以就會呼叫。</li>
+</ul>
+
+<div class="note">
+<p><strong>注意:</strong>再次重申,在原型鍊中的函式與屬性並<strong>不是</strong>從任一物件複製到另一個物件,而是如上述的,沿著該原型鍊向上存取而得。</p>
+</div>
+
+<div class="note">
+<p><strong>注意:</strong>直接存取物件的原型物件,並沒有一定的方式。原型鍊中,項目之間的「連結」均定義於內部屬性之內,即 JavaScript 規格中的 <code>[[prototype]]</code> (可參閱 {{glossary("ECMAScript")}})。新版瀏覽器均具備所謂的「<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto">__proto__</a></code> (兩邊都是 2 個底線)」屬性,其中就包含了物件的原型物件。舉例來說,你可嘗試「<code>person1.__proto__」</code>與「<code>person1.__proto__.__proto__</code>」看看程式碼中的鍊會是什麼樣子!</p>
+</div>
+
+<h2 id="原型屬性也定義所要繼承的成員">原型屬性也定義所要繼承的成員</h2>
+
+<p>所以該在哪裡定義所要繼承的屬性與函式呢?若看一下 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a></code> 參考頁面,你就會看到左邊列出許多屬性與函式,遠超過上方擷圖所列 <code>person1</code> 物件所繼承的成員數量。有些繼承了,有些則無?為什麼呢?</p>
+
+<p>原因在於,繼承的成員就是在 <code>prototype</code> 屬性 (你也能稱之為子命名空間 sub namespace) 中定義的成員,也就是以「<code>Object.prototype.」開頭的成員;並非只以「</code><code>Object.」開頭的成員。</code><code>prototype</code> 屬性值就是 1 個物件,基本上儲存了許多我們想「讓原型鍊上的物件一路繼承下去」的屬性與函式。</p>
+
+<p>所以如 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch">Object.prototype.watch()</a></code>、<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf">Object.prototype.valueOf()</a></code> 等等,均可用於繼承自 <code>Object()</code> 的任何物件類型,包含以建構子建立的新物件實例。</p>
+
+<p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is">Object.is()</a></code>、<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys">Object.keys()</a></code>,及其他未於 <code>prototype</code> 內定義的成員,也就不會繼承至 1). 物件實例或 2). 從 <code>Object() 繼承而來的物件類型。</code>這些函式\屬性都只能用於 <code>Object()</code> 建構子本身。</p>
+
+<div class="note">
+<p><strong>注意:</strong>這看起來很奇怪:你怎麼能在建構子上定義函式 (Method),而且這建構子本身也是函式 (Function)?其實「Function」也屬於一個物件類型,可參閱 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function">Function()</a></code> 建構子參考以進一步了解。</p>
+</div>
+
+<ol>
+ <li>你可自行檢查現有的原型屬性。回到我們之前的範例,試著於 JavaScript 主控台中輸入:
+ <pre class="brush: js">Person.prototype</pre>
+ </li>
+ <li>輸出結果很平淡,畢竟我們並未在自定的建構子原型上定義任何東西。依預設值,建構子的 <code>prototype</code> 都是從空白開始。現在可嘗試下列:
+ <pre class="brush: js">Object.prototype</pre>
+ </li>
+</ol>
+
+<p>這樣就會看到 <code>Object</code> 的 <code>prototype</code> 屬性中所定義的許多函式,而繼承自 <code>Object</code> 的物件也能找到這些函式。</p>
+
+<p>只要試著尋找如 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></code>、<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date">Date</a></code>、<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number">Number</a></code>、<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></code> 等全域物件的原型上定義的函式與屬性,就會看到 JavaScript 中的其他原型鍊繼承範例。這些物件都在其原型上定義了多個成員,因此可作為你建立字串時的範例:</p>
+
+<pre class="brush: js">var myString = 'This is my string.';</pre>
+
+<p><code>myString</code> 上立刻就有多個有用的函式,如 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split">split()</a></code>、<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf">indexOf()</a></code>、<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace">replace()</a></code> 等。</p>
+
+<div class="warning">
+<p><strong>重要:</strong><code>prototype</code> 這個屬性,是 JavaScript 中最讓人混淆的名稱之一。你可能會認為<code>this</code>屬性即指目前物件(current object)的原型物件(prototype object),但它其實不是原型 (應該是可透過 <code>__proto__</code> 存取的內部物件(internal object)才對,記得上面說過的嗎?)。<code>prototype</code>是一個物件(object),內含了你定義所應該繼承的成員。</p>
+</div>
+
+<h2 id="再次溫習_create()">再次溫習 create()</h2>
+
+<p>我們先前講過用 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create">Object.create()</a></code> 函式建立新物件實例的方法。</p>
+
+<ol>
+ <li>舉例來說,你可先在前面的 JavaScript 主控台範例中試著輸入:
+ <pre class="brush: js">var person2 = Object.create(person1);</pre>
+ </li>
+ <li><code>create()</code> 實際上是透過特定的原型物件,來建立新的物件。我們在這裡將 <code>person1</code> 作為原型物件,建立了 <code>person2</code>。你可於主控台輸入下列以測試之:
+ <pre class="brush: js">person2.__proto__</pre>
+ </li>
+</ol>
+
+<p>如此將回傳 <code>person1</code> 物件。</p>
+
+<h2 id="建構子的屬性">建構子的屬性</h2>
+
+<p>每個物件實例都具備 1 個<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor">建構子</a></code>屬性,指向「用以建立實例」的原始建構子函式。</p>
+
+<ol>
+ <li>舉例來說,若在主控台中輸入下列指令:
+ <pre class="brush: js">person1.constructor
+person2.constructor</pre>
+
+ <p>應該兩者都會回傳 <code>Person()</code> 建構子,因為此建構子包含這些實例的原始定義。</p>
+
+ <p>偷吃步的方法,是將圓括弧加到 <code>constructor</code> 屬性 (須包含任何必要參數) 末端,以從該建構子建立其他物件實例。畢竟建構子也是函式 (Function),所以可透過圓括弧將之觸發。你只要納入 <code>new</code> 這個關鍵字,即可將此函式作為建構子。</p>
+ </li>
+ <li>在主控台中輸入:
+ <pre class="brush: js">var person3 = new person1.constructor('Karen', 'Stephenson', 26, 'female', ['playing drums', 'mountain climbing']);</pre>
+ </li>
+ <li>現在可試著存取新物件的功能,例如:
+ <pre class="brush: js">person3.name.first
+person3.age
+person3.bio()</pre>
+ </li>
+</ol>
+
+<p>這樣運作得還不差。你不需常常用這方法,但當你要建立新的實例,又因為某些原因找不到原始建構子的參照,這就特別有用了。</p>
+
+<p>此外,<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor">constructor</a></code> 屬性還有其他用處。舉例來說,如果你有個物件實例,並要回傳建構子 (本身就是實例) 的名稱,就透過:</p>
+
+<pre class="brush: js">instanceName.constructor.name</pre>
+
+<p>也可嘗試:</p>
+
+<pre class="brush: js">person1.constructor.name</pre>
+
+<h2 id="修改原型">修改原型</h2>
+
+<p>先看看建構子的 <code>prototype</code> 屬性的修改範例:</p>
+
+<ol>
+ <li>回到 <a href="http://mdn.github.io/learning-area/javascript/oojs/introduction/oojs-class-further-exercises.html">oojs-class-further-exercises.html</a> 範例,先在本機儲存 1 份<a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/introduction/oojs-class-further-exercises.html">原始碼</a>的副本。在現成的 JavaScript 中加入下列程式碼,即是將新函式新增到建構子的 <code>prototype</code> 屬性:
+
+ <pre class="brush: js">Person.prototype.farewell = function() {
+ alert(this.name.first + ' has left the building. Bye for now!');
+}</pre>
+ </li>
+ <li>儲存程式碼並在瀏覽器中載入頁面,再輸入下列程式碼:
+ <pre class="brush: js">person1.farewell();</pre>
+ </li>
+</ol>
+
+<p>這時應該會看到警示訊息且內含了建構子所定義的人名。這樣很有用,但如果能動態更新整個繼承鍊,且從建構子分割出來的所有物件實例都能使用此新的函式,就會更有用!</p>
+
+<p>花個 1 分鐘想想,我們的程式碼中定義了建構子,然後根據建構子建立實例物件,接著將新函式添增到建構子的原型:</p>
+
+<pre class="brush: js">function Person(first, last, age, gender, interests) {
+
+ // property and method definitions
+
+};
+
+var person1 = new Person('Tammi', 'Smith', 32, 'neutral', ['music', 'skiing', 'kickboxing']);
+
+Person.prototype.farewell = function() {
+ alert(this.name.first + ' has left the building. Bye for now!');
+}</pre>
+
+<p>但是 <code>farewell()</code> 函式仍可用於 <code>person1</code> 物件實例,其可用的功能已自動更新過。如此證明了我們之前對原型鍊的說明,也代表瀏覽器會沿著鍊往上找「尚未於物件實例上定義的函式」,而非「複製到實例中的函式」。如此可建構強大且靈活的系統。</p>
+
+<div class="note">
+<p><strong>注意:</strong>如果你在讓此範例運作時感覺有點困難,可參閱 <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/advanced/oojs-class-prototype.html">oojs-class-prototype.html</a> 範例 (也可看<a href="http://mdn.github.io/learning-area/javascript/oojs/advanced/oojs-class-prototype.html">即時運作</a>的情形)。</p>
+</div>
+
+<p>你很少會看到在 <code>prototype</code> 屬性上定義的屬性,因為照此範例定義的屬性彈性較低,舉例來說,你可新增如下的屬性:</p>
+
+<pre class="brush: js">Person.prototype.fullName = 'Bob Smith';</pre>
+
+<p>但因為幾乎不會有人取這名字,所以就沒什麼彈性。最好可以在 <code>name.first</code> 與 <code>name.last 之外建立 fullName:</code></p>
+
+<pre class="brush: js">Person.prototype.fullName = this.name.first + ' ' + this.name.last;</pre>
+
+<p>但因為這樣會參照全域範圍,而非函式範圍,所以也不適用。若呼叫此屬性,則將回傳 <code>undefined undefined</code>。這種模式適合我們先前於原型中定義的函式,因為該函式就是在功能範圍之內,且可成功轉移至物件實例的的範圍。因此你可能會在原型中定義常數屬性 (也就是永遠不需更改的屬性),但一般來說會比較適合在建構子中定義屬性。</p>
+
+<p>事實上,許多物件定義較常見的模式,就是在建構子中定義屬性,而在原型中定義函式。這樣一來,建構子只有屬性定義;函式則切分到不同的區塊,讓整個程式碼較清楚易讀。舉例來說:</p>
+
+<pre class="brush: js">// Constructor with property definitions
+
+function Test(a,b,c,d) {
+ // property definitions
+};
+
+// First method definition
+
+Test.prototype.x = function () { ... }
+
+// Second method definition
+
+Test.prototype.y = function () { ... }
+
+// etc.</pre>
+
+<p>你可在 Piotr Zalewa 的「<a href="https://github.com/zalun/school-plan-app/blob/master/stage9/js/index.js">school plan app</a>」範例中看到實際運作的範例。</p>
+
+<h2 id="摘要">摘要</h2>
+
+<p>本文說明了 JavaScript 物件原型,包含原型物件鍊是如何讓物件能互相繼承其特性、原型屬性的本質、原型屬性又是如何能將函式新增至建構子,以及其他相關概念。</p>
+
+<p>接著我們將讓你在自己的任 2 個自訂物件之間,實作功能的繼承。</p>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects")}}</p>