aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/javascript/reference/errors/redeclared_parameter/index.html
blob: e9ba8cbbe0da765b8341dd04429a6cc2e03eb7b3 (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
---
title: 'SyntaxError: redeclaration of formal parameter "x"'
slug: Web/JavaScript/Reference/Errors/Redeclared_parameter
translation_of: Web/JavaScript/Reference/Errors/Redeclared_parameter
---
<div>{{jsSidebar("Errors")}}</div>

<h2 id="訊息">訊息</h2>

<pre class="syntaxbox">SyntaxError: redeclaration of formal parameter "x" (Firefox)
SyntaxError: Identifier "x" has already been declared (Chrome)
</pre>

<h2 id="錯誤類型">錯誤類型</h2>

<p>{{jsxref("SyntaxError")}}</p>

<h2 id="哪裡錯了?">哪裡錯了?</h2>

<p>當相同的變數名作為函式的參數、接著又在函式體(function body)內用了 <code><a href="/zh-TW/docs/Web/JavaScript/Reference/Statements/let">let</a></code> 重複宣告並指派時出現。在 JavaScript 裡面,不允許在相同的函式、或是作用域區塊(block scope)內重複宣告相同的 <code>let</code> 變數。</p>

<h2 id="實例">實例</h2>

<p>在這裡,「arg」變數的參數被重複宣告。</p>

<pre class="brush: js example-bad">function f(arg) {
  let arg = 'foo';
}

// SyntaxError: redeclaration of formal parameter "arg"
</pre>

<p>If you want to change the value of "arg" in the function body, you can do so, but you do not need to declare the same variable again. In other words: you can omit the <code>let</code> keyword. If you want to create a new variable, you need to rename it as conflicts with the function parameter already.</p>

<pre class="brush: js example-good">function f(arg) {
  arg = 'foo';
}

function f(arg) {
  let bar = 'foo';
}
</pre>

<h2 id="相容性註解">相容性註解</h2>

<ul>
 <li>在 Firefox 49 {{geckoRelease(49)}} 之前,這個錯誤被歸為 {{jsxref("TypeError")}}。 ({{bug(1275240)}})</li>
</ul>

<h2 id="參見">參見</h2>

<ul>
 <li><code><a href="/zh-TW/docs/Web/JavaScript/Reference/Statements/let">let</a></code></li>
 <li><code><a href="/zh-TW/docs/Web/JavaScript/Reference/Statements/const">const</a></code></li>
 <li><code><a href="/zh-TW/docs/Web/JavaScript/Reference/Statements/var">var</a></code></li>
 <li><a href="/zh-TW/docs/Web/JavaScript/Guide">JavaScript 教學</a><a href="/zh-TW/docs/Web/JavaScript/Guide/Grammar_and_Types#Declarations">宣告變數</a> </li>
</ul>