diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:43:23 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:43:23 -0500 |
commit | 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 (patch) | |
tree | a9ef8ac1e1b8fe4207b6d64d3841bfb8990b6fd0 /files/zh-tw/web/javascript/guide/numbers_and_dates | |
parent | 074785cea106179cb3305637055ab0a009ca74f2 (diff) | |
download | translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.gz translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.bz2 translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.zip |
initial commit
Diffstat (limited to 'files/zh-tw/web/javascript/guide/numbers_and_dates')
-rw-r--r-- | files/zh-tw/web/javascript/guide/numbers_and_dates/index.html | 383 |
1 files changed, 383 insertions, 0 deletions
diff --git a/files/zh-tw/web/javascript/guide/numbers_and_dates/index.html b/files/zh-tw/web/javascript/guide/numbers_and_dates/index.html new file mode 100644 index 0000000000..88ed75fd3e --- /dev/null +++ b/files/zh-tw/web/javascript/guide/numbers_and_dates/index.html @@ -0,0 +1,383 @@ +--- +title: 數字與日期 +slug: Web/JavaScript/Guide/Numbers_and_dates +translation_of: Web/JavaScript/Guide/Numbers_and_dates +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}</div> + +<p class="summary">這個章節將介紹如何在 JavaScript 中處理數字與日期。</p> + +<h2 id="數字Numbers">數字(Numbers)</h2> + +<p>在 JavaScript 中, Number所使用的標準依照 <a class="external external-icon" href="https://en.wikipedia.org/wiki/Double-precision_floating-point_format">double-precision 64-bit binary format IEEE 754</a> (i.e. number的區間是 -(2<sup>53</sup> -1) 到 2<sup>53</sup> -1)。<strong>整數是沒有特定的類型</strong>。</p> + +<p>此外還可以顯示浮點數,三種符號數值: <code>+</code>{{jsxref("Infinity")}}, <code>-</code>{{jsxref("Infinity")}}, and {{jsxref("NaN")}} (not-a-number)。</p> + +<p>{{jsxref("BigInt")}} 是Javascript最新的功能,它可以表示一個很大的整數。使用 <code>BigInt需要注意一點</code>,<code>BigInt</code> 和{{jsxref("Number")}}不能在同一個operation混用還有當用 {{jsxref("Math")}} 物件時不能使用<code>BigInt</code>。</p> + +<p>請參照 <a href="/en-US/docs/Web/JavaScript/Data_structures">JavaScript data types and structures</a> 來取得更多詳細資料。</p> + +<p>你可以用四種進制表示數字:十進制 (decimal),二進制 (binary),八進制 (octal) 以及十六進制 (hexadecimal)。</p> + +<h3 id="十進制數值">十進制數值</h3> + +<pre class="brush: js notranslate">1234567890 +42 + +// 以零為開頭時要小心: + +0888 // 888 解析為 十進制數值 +0777 // 在 non-strict 模式下將解析成八進制 (等同於十進制的 511) +</pre> + +<p>請注意,十進位數字允許第一個數字設為零(<code>0</code>)的話,前提是後面接的數字必須要有一個數字大於8(例如輸入0888結果會是888,輸入068結果會是68),不然則會被轉成8進位(例如0777結果會是511,輸入063結果會是51)。</p> + +<h3 id="二進制數值">二進制數值</h3> + +<p>二進制數值以 0 為開頭並跟著一個大寫或小寫的英文字母 「B」 (<code>0b</code> 或 <code>0B</code>)。如果 <code>0b</code> 後面接著的數字不是 0 或 1,那會丟出 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError(語法錯誤)</a></code>: "Missing binary digits after 0b"。</p> + +<pre class="brush: js notranslate">var FLT_SIGNBIT = 0b10000000000000000000000000000000; // 2147483648 +var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040 +var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607</pre> + +<h3 id="八進制數值">八進制數值</h3> + +<p>八進制數值以 0 為開頭。如果 <code>0</code> 後面的數字超出 0 到 7 這個範圍,將會被解析成十進制數值。</p> + +<pre class="brush: js notranslate">var n = 0755; // 493 +var m = 0644; // 420 +</pre> + +<p>Strict mode in ECMAScript 5 forbids octal syntax. Octal syntax isn't part of ECMAScript 5, but it's supported in all browsers by prefixing the octal number with a zero: <code>0644 === 420</code> and<code>"\045" === "%"</code>. In ECMAScript 2015, octal numbers are supported if they are prefixed with <code>0o</code>, e.g.: </p> + +<pre class="brush: js notranslate">var a = 0o10; // ES2015: 8 +</pre> + +<h3 id="十六進制數值">十六進制數值</h3> + +<p>十六進制數值以 0 為開頭並跟著一個大寫或小寫的英文字母 「X」(<code>0x</code> 或 <code>0X</code>)。如果 <code>0b</code> 後面接著的值超出範圍 (0123456789ABCDEF),那會丟出 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError(語法錯誤)</a></code>:"Identifier starts immediately after numeric literal"。</p> + +<pre class="brush: js notranslate">0xFFFFFFFFFFFFFFFFF // 295147905179352830000 +0x123456789ABCDEF // 81985529216486900 +0XA // 10 +</pre> + +<h3 id="指數運算">指數運算</h3> + +<pre class="brush: js notranslate">1E3 // 1000 +2e6 // 2000000 +0.1e2 // 10</pre> + +<h2 id="Number_物件"><code>Number</code> 物件</h2> + +<p>The built-in {{jsxref("Number")}} object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You cannot change the values of these properties and you use them as follows:</p> + +<pre class="brush: js notranslate">var biggestNum = Number.MAX_VALUE; +var smallestNum = Number.MIN_VALUE; +var infiniteNum = Number.POSITIVE_INFINITY; +var negInfiniteNum = Number.NEGATIVE_INFINITY; +var notANum = Number.NaN; +</pre> + +<p>You always refer to a property of the predefined <code>Number</code> object as shown above, and not as a property of a <code>Number</code> object you create yourself.</p> + +<p>下面這張表格整理了 <code>Number</code> 物件的屬性</p> + +<p><code style="font-weight: 700;">Number</code><strong style="font-style: inherit; font-weight: 700;"> 的屬性</strong></p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">屬性</th> + <th scope="col">描述</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Number.MAX_VALUE")}}</td> + <td>可表示的最大數值</td> + </tr> + <tr> + <td>{{jsxref("Number.MIN_VALUE")}}</td> + <td>可表示的最小數值</td> + </tr> + <tr> + <td>{{jsxref("Number.NaN")}}</td> + <td>表示「非數值」(Not-A-Number)的數值</td> + </tr> + <tr> + <td>{{jsxref("Number.NEGATIVE_INFINITY")}}</td> + <td>Special negative infinite value; returned on overflow</td> + </tr> + <tr> + <td>{{jsxref("Number.POSITIVE_INFINITY")}}</td> + <td>Special positive infinite value; returned on overflow</td> + </tr> + <tr> + <td>{{jsxref("Number.EPSILON")}}</td> + <td>Difference between one and the smallest value greater than one that can be represented as a {{jsxref("Number")}}.</td> + </tr> + <tr> + <td>{{jsxref("Number.MIN_SAFE_INTEGER")}}</td> + <td>可以在 JavaScript 中安全表示的最小數值。</td> + </tr> + <tr> + <td>{{jsxref("Number.MAX_SAFE_INTEGER")}}</td> + <td>可以在 JavaScript 中安全表示的最大數值。</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption><code>Number</code> 的方法</caption> + <thead> + <tr> + <th>方法</th> + <th>描述</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Number.parseFloat()")}}</td> + <td>字串轉換成浮點數。<br> + 等同於全域函式 {{jsxref("parseFloat", "parseFloat()")}} 。</td> + </tr> + <tr> + <td>{{jsxref("Number.parseInt()")}}</td> + <td>以指定的基數將字串轉換成整數。<br> + 等同於全域函式 {{jsxref("parseInt", "parseInt()")}} 。</td> + </tr> + <tr> + <td>{{jsxref("Number.isFinite()")}}</td> + <td>判定給定的值是不是一個有限數。</td> + </tr> + <tr> + <td>{{jsxref("Number.isInteger()")}}</td> + <td>判定給定的值是不是一個整數</td> + </tr> + <tr> + <td>{{jsxref("Number.isNaN()")}}</td> + <td>Determines whether the passed value is {{jsxref("Global_Objects/NaN", "NaN")}}. More robust version of the original global {{jsxref("Global_Objects/isNaN", "isNaN()")}}.</td> + </tr> + <tr> + <td>{{jsxref("Number.isSafeInteger()")}}</td> + <td>Determines whether the provided value is a number that is a <dfn>safe integer</dfn>.</td> + </tr> + </tbody> +</table> + +<p>The <code>Number</code> prototype provides methods for retrieving information from <code>Number</code> objects in various formats. The following table summarizes the methods of <code>Number.prototype</code>.</p> + +<table class="standard-table"> + <caption><code>Number.prototype</code> 的方法</caption> + <thead> + <tr> + <th scope="col">方法</th> + <th scope="col">描述</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Number.toExponential", "toExponential()")}}</td> + <td>Returns a string representing the number in exponential notation.</td> + </tr> + <tr> + <td>{{jsxref("Number.toFixed", "toFixed()")}}</td> + <td>Returns a string representing the number in fixed-point notation.</td> + </tr> + <tr> + <td>{{jsxref("Number.toPrecision", "toPrecision()")}}</td> + <td>Returns a string representing the number to a specified precision in fixed-point notation.</td> + </tr> + </tbody> +</table> + +<h2 id="Math_物件"><code>Math</code> 物件</h2> + +<p>The built-in {{jsxref("Math")}} object has properties and methods for mathematical constants and functions. For example, the <code>Math</code> object's <code>PI</code> property has the value of pi (3.141...), which you would use in an application as</p> + +<pre class="brush: js notranslate">Math.PI +</pre> + +<p>Similarly, standard mathematical functions are methods of <code>Math</code>. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write</p> + +<pre class="brush: js notranslate">Math.sin(1.56) +</pre> + +<p>Note that all trigonometric methods of <code>Math</code> take arguments in radians.</p> + +<p>The following table summarizes the <code>Math</code> object's methods.</p> + +<table class="standard-table"> + <caption><code>Math</code> 的方法</caption> + <thead> + <tr> + <th scope="col">方法</th> + <th scope="col">描述</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Math.abs", "abs()")}}</td> + <td>絕對值</td> + </tr> + <tr> + <td>{{jsxref("Math.sin", "sin()")}}, {{jsxref("Math.cos", "cos()")}}, {{jsxref("Math.tan", "tan()")}}</td> + <td>三角函數; 引數以弳度表示</td> + </tr> + <tr> + <td>{{jsxref("Math.asin", "asin()")}}, {{jsxref("Math.acos", "acos()")}}, {{jsxref("Math.atan", "atan()")}}, {{jsxref("Math.atan2", "atan2()")}}</td> + <td>反三角函數; 回傳值以弳度表示</td> + </tr> + <tr> + <td>{{jsxref("Math.sinh", "sinh()")}}, {{jsxref("Math.cosh", "cosh()")}}, {{jsxref("Math.tanh", "tanh()")}}</td> + <td>雙曲函數; 引數以 hyperbolic angle 表示</td> + </tr> + <tr> + <td>{{jsxref("Math.asinh", "asinh()")}}, {{jsxref("Math.acosh", "acosh()")}}, {{jsxref("Math.atanh", "atanh()")}}</td> + <td>反雙曲函數; 回傳值以 hyperbolic angle 表示</td> + </tr> + <tr> + <td> + <p>{{jsxref("Math.pow", "pow()")}}, {{jsxref("Math.exp", "exp()")}}, {{jsxref("Math.expm1", "expm1()")}}, {{jsxref("Math.log10", "log10()")}}, {{jsxref("Math.log1p", "log1p()")}}, {{jsxref("Math.log2", "log2()")}}</p> + </td> + <td>指數及對數函式</td> + </tr> + <tr> + <td>{{jsxref("Math.floor", "floor()")}}, {{jsxref("Math.ceil", "ceil()")}}</td> + <td>回傳小於等於/大於等於指定數字的最大/最小整數</td> + </tr> + <tr> + <td>{{jsxref("Math.min", "min()")}}, {{jsxref("Math.max", "max()")}}</td> + <td>Returns lesser or greater (respectively) of comma separated list of numbers arguments</td> + </tr> + <tr> + <td>{{jsxref("Math.random", "random()")}}</td> + <td>回傳一個介於 0 到 1 之間的數值</td> + </tr> + <tr> + <td>{{jsxref("Math.round", "round()")}}, {{jsxref("Math.fround", "fround()")}}, {{jsxref("Math.trunc", "trunc()")}},</td> + <td>Rounding and truncation functions.</td> + </tr> + <tr> + <td>{{jsxref("Math.sqrt", "sqrt()")}}, {{jsxref("Math.cbrt", "cbrt()")}}, {{jsxref("Math.hypot", "hypot()")}}</td> + <td>Square root, cube root, Square root of the sum of square arguments.</td> + </tr> + <tr> + <td>{{jsxref("Math.sign", "sign()")}}</td> + <td>The sign of a number, indicating whether the number is positive, negative or zero.</td> + </tr> + <tr> + <td>{{jsxref("Math.clz32", "clz32()")}},<br> + {{jsxref("Math.imul", "imul()")}}</td> + <td>Number of leading zero bits in the 32-bit binary representation.<br> + The result of the C-like 32-bit multiplication of the two arguments.</td> + </tr> + </tbody> +</table> + +<p>Unlike many other objects, you never create a <code>Math</code> object of your own. You always use the built-in <code>Math</code> object.</p> + +<h2 id="Date_物件"><code>Date</code> 物件</h2> + +<p>JavaScript 沒有所謂日期(date)的數據型態(data type)。你可以使用 {{jsxref("Date")}} 物件及其方法去設定日期跟時間來滿足你的需求 。<code>Date</code> 物件有大量的設定取得操作日期的方法(method),但它沒有屬性。</p> + +<p>JavaScript 處理日期的方式跟Java類似。這兩個語言有許多一樣的date方法,且都將日期儲存為從1970年1月1號0時0分0秒以來的毫秒數(millisecond)。</p> + +<p><code>Date</code> 物件範圍是 -100,000,000 days to 100,000,000 days 以1970年1月1號0時0分0秒UTC為基準。</p> + +<p>創建一個<code>Date</code>物件:</p> + +<pre class="brush: js notranslate">var dateObjectName = new Date([parameters]); +</pre> + +<p>在這裡創建一個名為<code>dateObjectName</code> 的 <code>Date</code> 物件;它可以是一個新的物件或是某個以存在的物件當中的屬性。</p> + +<p>Calling <code>Date</code> without the <code>new</code> keyword returns a string representing the current date and time.</p> + +<p>The <code>parameters</code> in the preceding syntax can be any of the following:</p> + +<ul> + <li>Nothing: creates today's date and time. For example, <code>today = new Date();</code>.</li> + <li>A string representing a date in the following form: "Month day, year hours:minutes:seconds." For example, <code>var Xmas95 = new Date("December 25, 1995 13:30:00")</code>. If you omit hours, minutes, or seconds, the value will be set to zero.</li> + <li>A set of integer values for year, month, and day. For example, <code>var Xmas95 = new Date(1995, 11, 25)</code>.</li> + <li>A set of integer values for year, month, day, hour, minute, and seconds. For example, <code>var Xmas95 = new Date(1995, 11, 25, 9, 30, 0);</code>.</li> +</ul> + +<h3 id="Date_的方法"> <code>Date</code> 的方法</h3> + +<p>The <code>Date</code> object methods for handling dates and times fall into these broad categories:</p> + +<ul> + <li>"set" methods, for setting date and time values in <code>Date</code> objects.</li> + <li>"get" methods, for getting date and time values from <code>Date</code> objects.</li> + <li>"to" methods, for returning string values from <code>Date</code> objects.</li> + <li>parse and UTC methods, for parsing <code>Date</code> strings.</li> +</ul> + +<p>With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a <code>getDay</code> method that returns the day of the week, but no corresponding <code>setDay</code> method, because the day of the week is set automatically. These methods use integers to represent these values as follows:</p> + +<ul> + <li>Seconds and minutes: 0 到 59</li> + <li>Hours: 0 到 23</li> + <li>Day: 0 (星期日) 到 6 (星期六)</li> + <li>Date: 1 到 31 (這個月的第幾天)</li> + <li>Months: 0 (一月) 到 11 (十二月)</li> + <li>Year: years since 1900</li> +</ul> + +<p>舉例,假設你定義了一個日期如下:</p> + +<pre class="brush: js notranslate">var Xmas95 = new Date('December 25, 1995'); +</pre> + +<p>那 <code>Xmas95.getMonth()</code> 將會回傳 11, <code>Xmas95.getFullYear()</code> 會回傳 1995。</p> + +<p><code>getTime</code> 及 <code>setTime</code> 這兩個方法對於比較日期有幫助。 The <code>getTime</code> method returns the number of milliseconds since January 1, 1970, 00:00:00 for a <code>Date</code> object.</p> + +<p>For example, the following code displays the number of days left in the current year:</p> + +<pre class="brush: js notranslate">var today = new Date(); +var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month +endYear.setFullYear(today.getFullYear()); // Set year to this year +var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day +var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay; +var daysLeft = Math.round(daysLeft); //returns days left in the year +</pre> + +<p>This example creates a <code>Date</code> object named <code>today</code> that contains today's date. It then creates a <code>Date</code> object named <code>endYear</code> and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between <code>today</code> and <code>endYear</code>, using <code>getTime</code> and rounding to a whole number of days.</p> + +<p>The <code>parse</code> method is useful for assigning values from date strings to existing <code>Date</code> objects. For example, the following code uses <code>parse</code> and <code>setTime</code> to assign a date value to the <code>IPOdate</code> object:</p> + +<pre class="brush: js notranslate">var IPOdate = new Date(); +IPOdate.setTime(Date.parse('Aug 9, 1995')); +</pre> + +<h3 id="範例">範例</h3> + +<p>下面這個範例,<code>JSClock()</code> 這個函式將會以數位時鐘的格式回傳時間。</p> + +<pre class="brush: js notranslate">function JSClock() { + var time = new Date(); + var hour = time.getHours(); + var minute = time.getMinutes(); + var second = time.getSeconds(); + var temp = '' + ((hour > 12) ? hour - 12 : hour); + if (hour == 0) + temp = '12'; + temp += ((minute < 10) ? ':0' : ':') + minute; + temp += ((second < 10) ? ':0' : ':') + second; + temp += (hour >= 12) ? ' P.M.' : ' A.M.'; + return temp; +} +</pre> + +<p> <code>JSClock</code> 這個函式會先建立一個名為 <code>time</code> 的 <code>Date</code> 物件; 因為沒有提供任何引數,所以會放入目前的日期及時間。接著呼叫 <code>getHours</code> 、 <code>getMinutes</code> 以及 <code>getSeconds</code> 這三個方法將現在的時、分以及秒分別指定給 <code>hour</code> 、 <code>minute</code> 以及 <code>second</code> 這三個變數。</p> + +<p>接著的四行指令將會建立一個時間的字串。第一行的指令建立了一個變數 <code>temp</code>,以條件運算式指定值; 如果 <code>hour</code> 大於 12,那就指定 (<code>hour - 12</code>),不然會直接指定 <code>hour</code>, 但如果 <code>hour</code> 等於 0 , 則改為 12。</p> + +<p>接著下一行將 <code>minute</code> 加到 <code>temp</code> 中。如果 <code>minute</code> 小於 10, 則會在附加時補上一個零; 不然的話會直接加上冒號及分鐘數。秒數也是以同樣的作法附加到 <code>temp</code> 上。</p> + +<p>最後,判斷 <code>hour</code> 是不是大於等於 12 ,如果是就在 <code>temp</code> 加上 "P.M." ,不然就加上 "A.M."。</p> + +<p>{{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}</p> |