aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/learn/javascript/first_steps/variables
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:43:23 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:43:23 -0500
commit218934fa2ed1c702a6d3923d2aa2cc6b43c48684 (patch)
treea9ef8ac1e1b8fe4207b6d64d3841bfb8990b6fd0 /files/zh-tw/learn/javascript/first_steps/variables
parent074785cea106179cb3305637055ab0a009ca74f2 (diff)
downloadtranslated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.gz
translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.bz2
translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.zip
initial commit
Diffstat (limited to 'files/zh-tw/learn/javascript/first_steps/variables')
-rw-r--r--files/zh-tw/learn/javascript/first_steps/variables/index.html344
1 files changed, 344 insertions, 0 deletions
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>