aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/javascript/reference/statements/block/index.html
blob: 384e3c122391f32962456a7104e2d00f1d638dd5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
---
title: 區塊
slug: Web/JavaScript/Reference/Statements/block
translation_of: Web/JavaScript/Reference/Statements/block
---
<p>{{jsSidebar("Statements")}}</p>

<h2 id="總覽">總覽</h2>

<p>區塊陳述用來組合零個或多個陳述。我們使用一對大括號 { } 以界定區塊。</p>

<table class="standard-table">
 <tbody>
  <tr>
   <td class="header" colspan="2">陳述句</td>
  </tr>
  <tr>
   <td>Implemented in</td>
   <td>JavaScript 1.0</td>
  </tr>
  <tr>
   <td>ECMAScript edition</td>
   <td>ECMA-262 1st edition</td>
  </tr>
 </tbody>
</table>

<h2 id="語法">語法</h2>

<pre class="syntaxbox">{
  <var>陳述_1</var>
  <var>陳述_2</var>
  ...
  <var>陳述_n</var>
}
</pre>

<h3 id="參數">參數</h3>

<dl>
 <dt><code>陳述_1</code>, <code>陳述_2</code>, <code>陳述_n</code></dt>
 <dd>區塊陳述中的陳述句群。</dd>
</dl>

<h2 id="說明">說明</h2>

<p>區塊陳述通常配合流程控制陳述(如 <code>if</code><code>for</code><code>while</code>)一併使用。</p>

<h4 id="var"><code>var</code></h4>

<p>使用<code>var</code>區塊中定義的變數,其存取範圍是整個整個函式或是腳本,即為Execution Context的範圍中。</p>

<pre class="brush: js">var x = 1;
{
  var x = 2;
}
alert(x); // outputs 2
</pre>

<p>輸出結果是 2。因為var是宣告於整個腳本範圍中。</p>

<h4 id="let_和_const"><code>let </code><code>const</code></h4>

<p>當使用<code>let</code>或是<code>const</code>進行宣告時,其存取範圍是只有本身定義的區塊中。</p>

<pre class="brush: js line-numbers  language-js"><code class="language-js">let x = 1;
{
  let x = 2;
}
console.log(x); // logs 1</code></pre>

<h4 id="function"><code>function</code></h4>

<p>當function被呼叫時,會建立此function的Execution Context,因此在function區塊使用<code>var</code>整個function區塊中都可對其進行存取。</p>

<pre class="brush: js">function foo() {
    {
        var a = 'var';
        {
            let a = 'let';
            console.log(a);  // let
        }
    }
    console.log(a);  // var
}
foo();</pre>