blob: 9a537951807ce756a535102435218e8d3413c90f (
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
|
---
title: 'SyntaxError: redeclaration of formal parameter "x"'
slug: Web/JavaScript/Reference/Errors/Redeclared_parameter
tags:
- Errors
- JavaScript
- SyntaxError
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)
SyntaxError: Cannot declare a let variable twice: 'x' (WebKit)
</pre>
<h2 id="错误类型">错误类型</h2>
<p>{{jsxref("SyntaxError")}}</p>
<h2 id="哪里出错了">哪里出错了?</h2>
<p>某个变量名称已经作为函数参数出现了,但是又使用了 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a></code> 在函数体里重声明了。在JavaScript 中不允许使用let在相同的函数或块范围内重新声明相同的变量。</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>如果要更改函数体中的“arg”的值,可以像下面一样,但不需要再次声明同一个变量。 换句话说:你可以省略 let 关键字。 如果要创建一个新变量,则需要将其重命名,因为其与函数参数有冲突。</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="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a></code></li>
<li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a></code></li>
<li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/var">var</a></code></li>
<li><a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_Types#Declarations">Declaring variables</a> in the <a href="/en-US/docs/Web/JavaScript/Guide">JavaScript Guide</a></li>
</ul>
|