From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../reference/errors/already_has_pragma/index.html | 37 +++++ .../errors/array_sort_argument/index.html | 47 ++++++ .../reference/errors/bad_octal/index.html | 55 +++++++ .../reference/errors/bad_radix/index.html | 61 ++++++++ .../reference/errors/bad_regexp_flag/index.html | 104 +++++++++++++ .../errors/bad_return_or_yield/index.html | 52 +++++++ .../errors/called_on_incompatible_type/index.html | 63 ++++++++ .../index.html | 56 +++++++ .../errors/cant_access_property/index.html | 55 +++++++ .../index.html | 66 ++++++++ .../reference/errors/cant_delete/index.html | 58 +++++++ .../errors/cant_redefine_property/index.html | 50 ++++++ .../errors/cyclic_object_value/index.html | 76 +++++++++ .../reference/errors/dead_object/index.html | 49 ++++++ .../errors/delete_in_strict_mode/index.html | 69 +++++++++ .../index.html | 76 +++++++++ .../deprecated_expression_closures/index.html | 78 ++++++++++ .../reference/errors/deprecated_octal/index.html | 67 ++++++++ .../errors/deprecated_source_map_pragma/index.html | 109 +++++++++++++ .../errors/deprecated_string_generics/index.html | 104 +++++++++++++ .../errors/deprecated_tolocaleformat/index.html | 90 +++++++++++ .../reference/errors/equal_as_assign/index.html | 52 +++++++ .../for-each-in_loops_are_deprecated/index.html | 171 +++++++++++++++++++++ .../reference/errors/getter_only/index.html | 82 ++++++++++ .../errors/identifier_after_number/index.html | 48 ++++++ .../reference/errors/illegal_character/index.html | 73 +++++++++ .../errors/in_operator_no_object/index.html | 71 +++++++++ .../web/javascript/reference/errors/index.html | 28 ++++ .../errors/invalid_array_length/index.html | 77 ++++++++++ .../invalid_assignment_left-hand_side/index.html | 54 +++++++ .../errors/invalid_const_assignment/index.html | 90 +++++++++++ .../reference/errors/invalid_date/index.html | 54 +++++++ .../errors/invalid_for-in_initializer/index.html | 73 +++++++++ .../errors/invalid_for-of_initializer/index.html | 63 ++++++++ .../index.html | 56 +++++++ .../reference/errors/is_not_iterable/index.html | 126 +++++++++++++++ .../reference/errors/json_bad_parse/index.html | 111 +++++++++++++ .../errors/malformed_formal_parameter/index.html | 61 ++++++++ .../reference/errors/malformed_uri/index.html | 65 ++++++++ .../errors/missing_bracket_after_list/index.html | 56 +++++++ .../missing_colon_after_property_id/index.html | 76 +++++++++ .../missing_curly_after_function_body/index.html | 66 ++++++++ .../missing_curly_after_property_list/index.html | 51 ++++++ .../errors/missing_formal_parameter/index.html | 80 ++++++++++ .../errors/missing_initializer_in_const/index.html | 57 +++++++ .../missing_name_after_dot_operator/index.html | 67 ++++++++ .../index.html | 42 +++++ .../missing_parenthesis_after_condition/index.html | 69 +++++++++ .../missing_semicolon_before_statement/index.html | 81 ++++++++++ .../errors/more_arguments_needed/index.html | 48 ++++++ .../errors/negative_repetition_count/index.html | 45 ++++++ .../reference/errors/no_non-null_object/index.html | 65 ++++++++ .../reference/errors/no_properties/index.html | 36 +++++ .../reference/errors/no_variable_name/index.html | 83 ++++++++++ .../non_configurable_array_element/index.html | 81 ++++++++++ .../reference/errors/not_a_codepoint/index.html | 51 ++++++ .../reference/errors/not_a_constructor/index.html | 95 ++++++++++++ .../reference/errors/not_a_function/index.html | 167 ++++++++++++++++++++ .../reference/errors/not_defined/index.html | 66 ++++++++ .../reference/errors/precision_range/index.html | 96 ++++++++++++ .../errors/property_access_denied/index.html | 45 ++++++ .../reference/errors/read-only/index.html | 76 +++++++++ .../errors/redeclared_parameter/index.html | 62 ++++++++ .../index.html | 88 +++++++++++ .../errors/reserved_identifier/index.html | 79 ++++++++++ .../errors/resulting_string_too_large/index.html | 50 ++++++ .../reference/errors/stmt_after_return/index.html | 76 +++++++++ .../errors/strict_non_simple_params/index.html | 113 ++++++++++++++ .../reference/errors/too_much_recursion/index.html | 54 +++++++ .../typed_array_invalid_arguments/index.html | 76 +++++++++ .../reference/errors/undeclared_var/index.html | 68 ++++++++ .../reference/errors/undefined_prop/index.html | 64 ++++++++ .../reference/errors/unexpected_token/index.html | 50 ++++++ .../reference/errors/unexpected_type/index.html | 65 ++++++++ .../errors/unnamed_function_statement/index.html | 114 ++++++++++++++ .../errors/unterminated_string_literal/index.html | 67 ++++++++ .../reference/errors/var_hides_argument/index.html | 51 ++++++ .../index.html" | 52 +++++++ 78 files changed, 5505 insertions(+) create mode 100644 files/zh-cn/web/javascript/reference/errors/already_has_pragma/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/array_sort_argument/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/bad_octal/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/bad_radix/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/bad_regexp_flag/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/bad_return_or_yield/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/called_on_incompatible_type/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/cant_access_property/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/cant_define_property_object_not_extensible/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/cant_delete/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/cant_redefine_property/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/cyclic_object_value/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/dead_object/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/delete_in_strict_mode/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/deprecated_expression_closures/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/deprecated_octal/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/deprecated_source_map_pragma/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/deprecated_string_generics/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/deprecated_tolocaleformat/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/equal_as_assign/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/for-each-in_loops_are_deprecated/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/getter_only/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/identifier_after_number/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/illegal_character/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/in_operator_no_object/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/invalid_array_length/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/invalid_const_assignment/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/invalid_date/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/invalid_for-in_initializer/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/invalid_for-of_initializer/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/invalid_right_hand_side_instanceof_operand/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/is_not_iterable/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/json_bad_parse/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/malformed_formal_parameter/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/malformed_uri/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/missing_bracket_after_list/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/missing_colon_after_property_id/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/missing_curly_after_function_body/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/missing_curly_after_property_list/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/missing_formal_parameter/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/missing_initializer_in_const/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/missing_name_after_dot_operator/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_condition/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/missing_semicolon_before_statement/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/more_arguments_needed/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/negative_repetition_count/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/no_non-null_object/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/no_properties/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/no_variable_name/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/non_configurable_array_element/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/not_a_codepoint/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/not_a_constructor/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/not_a_function/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/not_defined/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/precision_range/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/property_access_denied/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/read-only/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/redeclared_parameter/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/reserved_identifier/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/resulting_string_too_large/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/stmt_after_return/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/strict_non_simple_params/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/too_much_recursion/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/typed_array_invalid_arguments/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/undeclared_var/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/undefined_prop/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/unexpected_token/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/unexpected_type/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/unnamed_function_statement/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/unterminated_string_literal/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/var_hides_argument/index.html create mode 100644 "files/zh-cn/web/javascript/reference/errors/\344\270\215\350\203\275\346\267\273\345\212\240\345\261\236\346\200\247/index.html" (limited to 'files/zh-cn/web/javascript/reference/errors') diff --git a/files/zh-cn/web/javascript/reference/errors/already_has_pragma/index.html b/files/zh-cn/web/javascript/reference/errors/already_has_pragma/index.html new file mode 100644 index 0000000000..28bf001e59 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/already_has_pragma/index.html @@ -0,0 +1,37 @@ +--- +title: 'Warning: -file- is being assigned a //# sourceMappingURL, but already has one' +slug: Web/JavaScript/Reference/Errors/Already_has_pragma +translation_of: Web/JavaScript/Reference/Errors/Already_has_pragma +--- +
{{jsSidebar("Errors")}}
+ +

消息

+ +
Warning: -file- is being assigned a //# sourceMappingURL, but already has one.
+ +

错误类型

+ +

一个警告。JavaScript 的执行不会中止。

+ +

哪里有问题?

+ +

对于给定的 JavaScript 源码,源码映射规定了不止一次。

+ +

JavaScript 源码通常被组合和压缩,使其从服务器传递更加高效。 使用了源码映射,调试器能够将执行的源码映射到原始的源码。 有两种指派源码映射的方式,通过注释,或者对 JavaScript 设置标题。

+ +

示例

+ +

使用文件中的注释来设置源码映射:

+ +
//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map
+ +

或者,你可以对你的 JavaScript 文件设置一个标题:

+ +
X-SourceMap: /path/to/file.js.map
+ +

另见

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/array_sort_argument/index.html b/files/zh-cn/web/javascript/reference/errors/array_sort_argument/index.html new file mode 100644 index 0000000000..1053ea058b --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/array_sort_argument/index.html @@ -0,0 +1,47 @@ +--- +title: 'TypeError: invalid Array.prototype.sort argument' +slug: Web/JavaScript/Reference/Errors/Array_sort_argument +tags: + - Errors + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Array_sort_argument +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
TypeError: invalid Array.prototype.sort argument (Firefox)
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

{{jsxref("Array.prototype.sort()")}} 的参数预期为 {{jsxref("undefined")}} 或者是一个比较操作数的函数。

+ +

示例

+ +

无效的

+ +
[1, 3, 2].sort(5);  // TypeError
+
+var cmp = { asc: (x, y) => x >= y, dsc : (x, y) => x <= y };
+[1, 3, 2].sort(cmp[this.key] || 'asc');  // TypeError
+
+ +

有效的

+ +
[1, 3, 2].sort();   // [1, 2, 3]
+
+
+var cmp = { asc: (x, y) => x >= y, dsc : (x, y) => x <= y };
+[1, 3, 2].sort(cmp[this.key || 'asc']); // [1, 2, 3]
+ +

相关

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/bad_octal/index.html b/files/zh-cn/web/javascript/reference/errors/bad_octal/index.html new file mode 100644 index 0000000000..2f9b5d477e --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/bad_octal/index.html @@ -0,0 +1,55 @@ +--- +title: 'SyntaxError: "x" is not a legal ECMA-262 octal constant' +slug: Web/JavaScript/Reference/Errors/Bad_octal +tags: + - Errors + - JavaScript + - SyntaxError + - 严格模式 +translation_of: Web/JavaScript/Reference/Errors/Bad_octal +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
Warning: SyntaxError: 08 is not a legal ECMA-262 octal constant.
+Warning: SyntaxError: 09 is not a legal ECMA-262 octal constant.
+
+ +

错误类型

+ +

仅在 strict mode 下出现 {{jsxref("SyntaxError")}} 警告。

+ +

哪里出错了?

+ +

十进制字面量可以以零作为开始(0),后面跟着其他十进制数,但是假如前导 0 之后的所有数字都小于 8,那么这个数就会被解析为一个八进制的数。因为 08 和 09 不是这样的,所以 JavaScript 会发出警告。

+ +

请注意,不推荐使用八进制字面值和八进制转义序列,并会产生另外的弃用警告。 在 ECMAScript 6 和更高版本里,语法使用前导零后跟小写或大写拉丁字母“O”(0o或0O)。更多信息请查看 lexical grammar

+ +
+

注意:现在仅 firefox 会产生此错误。

+
+ +

示例

+ +

无效的八进制数

+ +
"use strict";
+08;
+09;
+// SyntaxError: 08 is not a legal ECMA-262 octal constant
+// SyntaxError: octal literals and octal escape sequences are deprecated
+ +

有效的八进制数

+ +

Use a leading zero followed by the letter "o";

+ +
0O755;
+0o644;
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/bad_radix/index.html b/files/zh-cn/web/javascript/reference/errors/bad_radix/index.html new file mode 100644 index 0000000000..1c45f8b6dd --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/bad_radix/index.html @@ -0,0 +1,61 @@ +--- +title: 'RangeError: radix must be an integer' +slug: Web/JavaScript/Reference/Errors/Bad_radix +tags: + - JavaScript + - 范围错误 + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Bad_radix +--- +
{{jsSidebar("Errors")}}
+ +

消息

+ +
RangeError: radix must be an integer at least 2 and no greater than 36 (Firefox)
+RangeError: toString() radix argument must be between 2 and 36 (Chrome)
+
+ +

错误类型

+ +

{{jsxref("RangeError")}}

+ +

发生了什么错误?

+ +

在使用{{jsxref("Number.prototype.toString()")}}方法时使用了可选的基数参数,参数应该为一个2到36之间的整型(数字),返回对应数字的转换为字符串时表示的该进制对应的数字量。

+ +

为什么小于36呢?因为一个大于(包含等于)10的基数在使用时需要用一个字母表字符来代替。不能超过36是因为拉丁字母表中只有26个字符。

+ +

你可能会用到以下的常见基数:

+ + + +

示例

+ +

错误示例

+ +
(42).toString(0);
+(42).toString(1);
+(42).toString(37);
+(42).toString(150);
+// You cannot use a string like this for formatting:
+(12071989).toString("MM-dd-yyyy");
+
+ +

正确示例

+ +
(42).toString(2);     // "101010" (binary)
+(13).toString(8);     // "15"     (octal)
+(0x42).toString(10);  // "66"     (decimal)
+(100000).toString(16) // "186a0"  (hexadecimal)
+
+ +

参考

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/bad_regexp_flag/index.html b/files/zh-cn/web/javascript/reference/errors/bad_regexp_flag/index.html new file mode 100644 index 0000000000..6365649479 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/bad_regexp_flag/index.html @@ -0,0 +1,104 @@ +--- +title: 'SyntaxError: invalid regular expression flag "x"' +slug: Web/JavaScript/Reference/Errors/Bad_regexp_flag +tags: + - 语法错误 + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Bad_regexp_flag +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
SyntaxError: invalid regular expression flag "x" (Firefox)
+SyntaxError: Invalid regular expression flags (Chrome)
+
+ +

错误类型

+ +

{{jsxref("SyntaxError","语法错误")}}.

+ +

什么地方出错了?

+ +

在代码中出现了无效的正则表达式的标记。在一个正则表达式字面量中,由闭合的两条斜线组成一个模式,(正则表达式的)标记定义在第二个(斜线)标记之后。他们也可以通过{{jsxref("RegExp", "正则表达式")}} 对象的构造函数(第二个参数)来定义。正则表达式的标记可以单独或者任意次序的组合使用,但ECMAScript只规定了五个。

+ +

要使正则表达式包含标记,使用此语法:

+ +
var re = /pattern/flags;
+
+ +

+ +
var re = new RegExp('pattern', 'flags');
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
正则表达式标记
标记说明
g整体检索.
i忽略大小写检索.
m多行检索.
uUnicode; 将模式视为Unicode码点的序列
ysticky 检索将从目标字符串的当前位置开始匹配。参阅{{jsxref("RegExp.sticky", "sticky")}}
+ +

示例

+ +

只有5个有效的正则表达式标记。

+ +
/foo/bar;
+
+// SyntaxError: invalid regular expression flag "b"
+
+ +

你打算创建一个正则表达式吗?一个包含两条斜线的表达式被解释为一个正则表达式的字面量。

+ +
let obj = {
+  url: /docs/Web
+};
+
+// SyntaxError: invalid regular expression flag "W"
+
+ +

还是你想创建一个字符串呢?添加单引号或双引号创建一个字符串字面量。

+ +
let obj = {
+  url: '/docs/Web'
+};
+ +

有效的正则表达式标记

+ +

在JavaScript中允许的五个有效的正则表达式标记,参阅上表。

+ +
/foo/g;
+/foo/gim;
+/foo/uy;
+
+ +

相关页面

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/bad_return_or_yield/index.html b/files/zh-cn/web/javascript/reference/errors/bad_return_or_yield/index.html new file mode 100644 index 0000000000..f2a0fb3de0 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/bad_return_or_yield/index.html @@ -0,0 +1,52 @@ +--- +title: 'SyntaxError: return not in function' +slug: Web/JavaScript/Reference/Errors/Bad_return_or_yield +translation_of: Web/JavaScript/Reference/Errors/Bad_return_or_yield +--- +
{{jsSidebar("Errors")}}
+ +

错误信息

+ +
SyntaxError: return not in function
+SyntaxError: yield not in function
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}.

+ +

什么地方出错了?

+ +

return 返回的或者 yield 语句在函数 function 外被调用. 或许是少了一个花括号, return 返回的和 yield 语句必须是在一个函数里,因为它们会停止(暂停或恢复)函数的继续执行,然后返回。

+ +

范例

+ +
var cheer = function(score) {
+  if (score === 147)
+    return "Maximum!";
+  };
+  if (score > 100) {
+    return "Century!";
+  }
+}
+
+// SyntaxError: return not in function
+// 语法错误:不是在函数里返回
+ +

初次看好像没什么错误,但是上面这段代码在第一个 if 后面少了一个 “ { ”。正确的应该如下:

+ +
var cheer = function(score) {
+  if (score === 147) {
+    return "Maximum!";
+  }
+  if (score > 100) {
+    return "Century!";
+  }
+};
+ +

相关信息

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/called_on_incompatible_type/index.html b/files/zh-cn/web/javascript/reference/errors/called_on_incompatible_type/index.html new file mode 100644 index 0000000000..fa6c631c6e --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/called_on_incompatible_type/index.html @@ -0,0 +1,63 @@ +--- +title: X.prototype.y called on incompatible type +slug: Web/JavaScript/Reference/Errors/Called_on_incompatible_type +tags: + - JavaScript + - 类型错误 +translation_of: Web/JavaScript/Reference/Errors/Called_on_incompatible_type +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
TypeError: Function.prototype.toString called on incompatible object (Firefox)
+TypeError: Function.prototype.bind called on incompatible target (Firefox)
+TypeError: Method Set.prototype.add called on incompatible receiver undefined (Chrome)
+TypeError: Bind must be called on a function (Chrome)
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

当这个错误被抛出时,属于某个对象的函数被调用,但是没有提供给 this 与其所期望的函数类型一致的参数。

+ +

在调用 {{jsxref("Function.prototype.call()")}} 或{{jsxref("Function.prototype.apply()")}} 方法,但是为 this 提供的绑定对象与预期的不匹配时,这个问题就会出现。

+ +

该问题还会出现于将一个(存储在一个对象中的)函数提供给另外一个函数作为参数时。在这种情况下,函数所在的对象并非该函数的 this  绑定的目标对象。为了解决这个问题,你或者为其提供一个 lambda 表达式,该表达式完成函数要完成的任务,或者调用 {{jsxref("Function.prototype.bind()")}} 函数为 this 强制绑定期望的对象。

+ +

示例

+ +

错误示例

+ +
var mySet = new Set;
+['bar', 'baz'].forEach(mySet.add);
+// mySet.add is a function, but "mySet" is not captured as this.
+
+var myFun = function () {};
+['bar', 'baz'].forEach(myFun.bind);
+// myFun.bind is a function, but "myFun" is not captured as this.
+
+
+ +

正确示例

+ +
var mySet = new Set;
+['bar', 'baz'].forEach(mySet.add.bind(mySet));
+// This works due to binding "mySet" as this.
+
+var myFun = function () {};
+['bar', 'baz'].forEach(x => myFun.bind(x));
+// This works using the "bind" function. It creates a lambda forwarding the argument.
+
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html b/files/zh-cn/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html new file mode 100644 index 0000000000..c99aba5c30 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html @@ -0,0 +1,56 @@ +--- +title: 'ReferenceError: can''t access lexical declaration`X'' before initialization' +slug: Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init +tags: + - JavaScript + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init +--- +
{{jsSidebar("Errors")}}
+ +

消息提示

+ +
ReferenceError: assignment to undeclared variable "x" (Firefox)
+
+ +

错误类型

+ +

{{jsxref("ReferenceError")}}

+ +

哪里出错了?

+ +

词法变量在初始化之前被访问。该错误可以发生于任何语句块中,当使用 let 或 const 修饰的变量在初始化之前被访问的时候。

+ +

示例

+ +

非法情况

+ +

在这个例子中,变量 "foo" 在语句块中再次声明,导致未初始化。

+ +
function test(){
+   let foo = 33;
+   if (true) {
+      let foo = (foo + 55); // ReferenceError: can't access lexical declaration `foo' before initialization
+   }
+}
+test();
+
+ +

正确情况

+ +

在 if 语句块中修改变量 "foo" 的值,不应该在其中进行二次声明。

+ +
function test(){
+   let foo = 33;
+   if (true) {
+      foo = (foo + 55);
+   }
+}
+test();
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/cant_access_property/index.html b/files/zh-cn/web/javascript/reference/errors/cant_access_property/index.html new file mode 100644 index 0000000000..8f8d830d2c --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/cant_access_property/index.html @@ -0,0 +1,55 @@ +--- +title: 'TypeError: can''t access property "x" of "y"' +slug: Web/JavaScript/Reference/Errors/Cant_access_property +translation_of: Web/JavaScript/Reference/Errors/Cant_access_property +--- +
{{jsSidebar("Errors")}}
+ +

消息

+ +
TypeError: Unable to get property {x} of undefined or null reference (Edge)
+TypeError: can't access property {x} of {y} (Firefox)
+TypeError: {y} is undefined, can't access property {x} of it (Firefox)
+TypeError: {y} is null, can't access property {x} of it (Firefox)
+
+Examples:
+TypeError: x is undefined, can't access property "prop" of it
+TypeError: x is null, can't access property "prop" of it
+TypeError: can't access property "prop" of undefined
+TypeError: can't access property "prop" of null
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}.

+ +

哪里出错了?

+ +

访问了 {{jsxref("undefined")}} 或{{jsxref("null")}} 值的属性.

+ +

例子

+ +

无效情形

+ +
// 对于undefined 以及 null 值, substring 方法无法正常工作
+var foo = undefined;
+foo.substring(1); // TypeError: x is undefined, can't access property "substring" of it
+
+var foo = null;
+foo.substring(1); // TypeError: x is null, can't access property "substring" of it
+
+ +

解决问题

+ +

为了解决undefined 或 null 值的空指针问题,你可以使用 typeof 操作符, 比如.

+ +
if (typeof foo !== 'undefined') {
+  // 现在已经确认foo已定义,可以进一步操作.
+}
+ +

参考更多

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/cant_define_property_object_not_extensible/index.html b/files/zh-cn/web/javascript/reference/errors/cant_define_property_object_not_extensible/index.html new file mode 100644 index 0000000000..6d3d074a8e --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/cant_define_property_object_not_extensible/index.html @@ -0,0 +1,66 @@ +--- +title: 'TypeError: can''t define property "x": "obj" is not extensible' +slug: Web/JavaScript/Reference/Errors/Cant_define_property_object_not_extensible +tags: + - Error + - Errors + - JavaScript + - TypeError + - 类型错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Cant_define_property_object_not_extensible +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
TypeError: can't define property "x": "obj" is not extensible (Firefox)
+TypeError: Cannot define property: "x", object is not extensible. (Chrome)
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

通常情况下,对象是可以进行扩展的,即可以向其添加新的属性。然而当使用 {{jsxref("Object.preventExtensions()")}} 将一个对象标记为不再可以扩展的情况下,就无法对该对象添加在其被标记为不可扩展之前所拥有的属性之外的新属性了。

+ +

示例

+ +

严格模式下,向已经标记为不可扩展的对象添加新属性会报 TypeError 错误。而在非严格模式下,添加属性 “x” 会被静默忽略。

+ +
'use strict';
+
+var obj = {};
+Object.preventExtensions(obj);
+
+obj.x = 'foo';
+// TypeError: can't define property "x": "obj" is not extensible
+
+ +

严格模式和非严格模式下两种模式下,调用{{jsxref("Object.defineProperty()")}} 向标记为不可扩展的对象添加新属性都会报 TypeError 错误。

+ +
var obj = { };
+Object.preventExtensions(obj);
+
+Object.defineProperty(obj,
+  'x', { value: "foo" }
+);
+// TypeError: can't define property "x": "obj" is not extensible
+
+ +

为了修复这个错误,你可以彻底移除 {{jsxref("Object.preventExtensions()")}} 语句,或者将其移动位置,使得属性在对象被标记为不可扩展之前添加。当然如果不需要试图添加的属性的话,你也可以将其移除。

+ +
'use strict';
+
+var obj = {};
+obj.x = 'foo'; // add property first and only then prevent extensions
+
+Object.preventExtensions(obj);
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/cant_delete/index.html b/files/zh-cn/web/javascript/reference/errors/cant_delete/index.html new file mode 100644 index 0000000000..d92956f409 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/cant_delete/index.html @@ -0,0 +1,58 @@ +--- +title: 'TypeError: property "x" is non-configurable and can''t be deleted' +slug: Web/JavaScript/Reference/Errors/Cant_delete +tags: + - JavaScript + - 严格模式 + - 类型错误 + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Cant_delete +--- +
{{jsSidebar("Errors")}}
+ +

消息

+ +
TypeError: property "x" is non-configurable and can't be deleted. (Firefox)
+TypeError: Cannot delete property 'x' of #<Object> (Chrome)
+
+ +

错误类型

+ +

{{jsxref("TypeError")}} 只出现在严格模式下。

+ +

哪里有问题?

+ +

尝试删除某个属性,但是这个属性是 不可配置的configurable属性控制是否该属性能从对象上删除,以及它的属性(除了writable)能否被修改。

+ +

这个错误仅仅在严格模式下出现。在非严格模式下,这个操作返回 false

+ +

示例

+ +

不可配置的属性并不特别常见,但是它们可以使用 {{jsxref("Object.defineProperty()")}} 或 {{jsxref("Object.freeze()")}} 创建。

+ +
'use strict';
+var obj = Object.freeze({name: 'Elsa', score: 157});
+delete obj.score;  // TypeError
+
+'use strict';
+var obj = {};
+Object.defineProperty(obj, 'foo', {value: 2, configurable: false});
+delete obj.foo;  // TypeError
+
+'use strict';
+var frozenArray = Object.freeze([0, 1, 2]);
+frozenArray.pop();  // TypeError
+
+ +

也有一些内建于 JavaScript 的不可配置属性。你可能会尝试删除一个数学常量。

+ +
'use strict';
+delete Math.PI;  // TypeError
+ +

另见

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/cant_redefine_property/index.html b/files/zh-cn/web/javascript/reference/errors/cant_redefine_property/index.html new file mode 100644 index 0000000000..abba81b6f2 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/cant_redefine_property/index.html @@ -0,0 +1,50 @@ +--- +title: 'TypeError: can''t redefine non-configurable property "x"' +slug: Web/JavaScript/Reference/Errors/Cant_redefine_property +tags: + - JavaScript + - 类型错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Cant_redefine_property +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
TypeError: can't redefine non-configurable property "x" (Firefox)
+TypeError: Cannot redefine property: "x" (Chrome)
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

这种错误的起因在于试图给对象重新定义一个属性,但是该属性是不可配置的。 configurable 特性控制着该属性是否可以从对象中删除,以及它的各个特性(除 writable 之外)是否可以修改。通常使用对象初始化语句定义的对象属性是可配置的。而使用 {{jsxref("Object.defineProperty()")}} 定义的属性则默认不可配置。

+ +

示例

+ +

使用 object.defineProperty 创建的不可配置属性

+ +

在使用 {{jsxref("Object.defineProperty()")}} 创建属性的时候,如果没有明确将其设定为可配置的,那么创建出来的属性就是不可配置的。

+ +
var obj = Object.create({});
+Object.defineProperty(obj, "foo", {value: "bar"});
+
+Object.defineProperty(obj, "foo", {value: "baz"});
+// TypeError: can't redefine non-configurable property "foo"
+
+ +

如果想要稍后重新定义的话,那么需要将 "foo" 属性设置为可配置的。

+ +
var obj = Object.create({});
+Object.defineProperty(obj, "foo", {value: "bar", configurable: true});
+Object.defineProperty(obj, "foo", {value: "baz", configurable: true});
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/cyclic_object_value/index.html b/files/zh-cn/web/javascript/reference/errors/cyclic_object_value/index.html new file mode 100644 index 0000000000..9ab3cb7b02 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/cyclic_object_value/index.html @@ -0,0 +1,76 @@ +--- +title: 'TypeError: cyclic object value' +slug: Web/JavaScript/Reference/Errors/Cyclic_object_value +tags: + - Error + - JavaScript + - 类型错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Cyclic_object_value +--- +
{{jsSidebar("Errors")}}
+ +
当一段JSON中出现循环引用,使用{{jsxref("JSON.stringify()")}}这个方法去处理JSON时会报这个"cyclic object value"错误。
+ +

提示信息

+ +
TypeError: cyclic object value (Firefox)
+TypeError: Converting circular structure to JSON (Chrome and Opera)
+TypeError: Circular reference in value argument not supported (Edge)
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

当调用 {{jsxref("JSON.stringify()")}} 方法去处理循环引用结构的JSON会失败。

+ +

JSON标准参考链接:JSON format

+ +

示例

+ +

循环引用

+ +

在如下循环结构中:

+ +
var a = {};
+var b = {};
+a.child = b;
+b.child = a;
+
+ +

{{jsxref("JSON.stringify()")}} 将会报错

+ +
JSON.stringify(a);
+// TypeError: cyclic object value
+
+ +

要处理循环引用的JSON,可以使用支持这种结构的库(例如cycle.js)),或者自己实现。

+ +

下面代码展示了,可以通过指定替换函数({{jsxref("JSON.stringify()")}} 方法的第二个参数) 来检查转换成字符串之前是否有循环对象引用的存在。

+ +

注意:以下代码并不会保存循环引用的值。

+ +
var seen = [];
+
+var replacer = function(key, value) {
+  if (typeof value === "object" && value !== null) {
+    if (seen.indexOf(value) >= 0) {
+      return;
+    }
+    seen.push(value);
+  }
+  return value;
+};
+
+JSON.stringify(a, replacer);
+// "{"child":{}}"
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/dead_object/index.html b/files/zh-cn/web/javascript/reference/errors/dead_object/index.html new file mode 100644 index 0000000000..c974ec27b8 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/dead_object/index.html @@ -0,0 +1,49 @@ +--- +title: 'TypeError: can''t access dead object' +slug: Web/JavaScript/Reference/Errors/Dead_object +tags: + - JavaScript + - 插件 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Dead_object +--- +
{{JSSidebar("Errors")}}
+ +

错误提示

+ +
TypeError: can't access dead object
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

为了提高内存使用效率以及防止内存泄露,Firefox 浏览器不允许插件在 DOM 所在的父页面被销毁后对 DOM 对象保持强引用。死对象指的是在 DOM 被销毁后依然持有对 DOM 元素的强引用(处于活跃状态)。为了避免这样的问题,对处于外部文档中的 DOM 节点的引用应该被存储于一个专属于那个文档的对象当中,并且在文档卸载的时候将其清理,或者使用弱引用方式进行存储。

+ +

Checking if an object is dead

+ +

Components.utils offers a isDeadWrapper() method, which privileged code might use.

+ +
if (Components.utils.isDeadWrapper(window)) {
+  // dead
+}
+ +

Unprivileged code has no access to Component.utils and might just be able catch the exception.

+ +
try {
+  String(window);
+}
+catch (e) {
+  console.log("window is likely dead");
+}
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/delete_in_strict_mode/index.html b/files/zh-cn/web/javascript/reference/errors/delete_in_strict_mode/index.html new file mode 100644 index 0000000000..aa9a3293ae --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/delete_in_strict_mode/index.html @@ -0,0 +1,69 @@ +--- +title: >- + SyntaxError: applying the 'delete' operator to an unqualified name is + deprecated +slug: Web/JavaScript/Reference/Errors/Delete_in_strict_mode +tags: + - JavaScript + - 语法错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Delete_in_strict_mode +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated (Firefox)
+SyntaxError: Delete of an unqualified identifier in strict mode. (Chrome)
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}} 仅出现在严格模式下。

+ +

哪里出错了?

+ +

在 JavaScript 中,普通变量是不能通过 delete 操作符来删除的。在严格模式下,试图去删除一个变量会报错,这是不允许的。

+ +

delete 操作符只能用于删除对象中的属性。只有可配置的对象属性才“符合”被删除的条件。

+ +

与一般流行的观点相反的是, delete 操作符与直接释放内存无关。内存管理是通过切断引用来间接实现的。可以参考内存管理页面与 delete 操作符页面来获取更多的细节信息。

+ +

这个错误提示只出现于严格模式。在非严格模式下,该操作返回 false。

+ +

示例

+ +

在 JavaScript 中,普通变量是不能删除的,在严格模式下会报错:

+ +
'use strict';
+
+var x;
+
+// ...
+
+delete x;
+
+// SyntaxError: applying the 'delete' operator to an unqualified name
+// is deprecated
+
+ +

要释放变量引用的内容,可以将变量值设置为 {{jsxref("null")}}:

+ +
'use strict';
+
+var x;
+
+// ...
+
+x = null;
+
+// x can be garbage collected
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.html b/files/zh-cn/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.html new file mode 100644 index 0000000000..cfafd9c155 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.html @@ -0,0 +1,76 @@ +--- +title: 'ReferenceError: deprecated caller or arguments usage' +slug: Web/JavaScript/Reference/Errors/Deprecated_caller_or_arguments_usage +tags: + - Errors + - JavaScript + - Strict Mode + - 严格模式 + - 警告 +translation_of: Web/JavaScript/Reference/Errors/Deprecated_caller_or_arguments_usage +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
Warning: ReferenceError: deprecated caller usage (Firefox)
+Warning: ReferenceError: deprecated arguments usage (Firefox)
+TypeError: 'callee' and 'caller' cannot be accessed in strict mode. (Safari)
+
+ +

错误类型

+ +

仅在严格模式下出现的 {{jsxref("ReferenceError")}} 警告。JavaScript 的执行将不会停止。

+ +

发生了什么?

+ +

strict mode 中,{{jsxref("Function.caller")}} 和 {{jsxref("Function.arguments")}} 属性是不该使用的。它们都是已经被废弃的了,因为这两者泄露了函数的调用者,是不标准的,难于优化和有这潜在的性能问题。

+ +

实力

+ +

废弃的 function.caller or arguments.callee.caller

+ +

{{jsxref("Function.caller")}} 和 arguments.callee.caller 都是已废弃的 (详见参考文章)。

+ +
"use strict";
+
+function myFunc() {
+  if (myFunc.caller == null) {
+    return 'The function was called from the top!';
+  } else {
+    return 'This function\'s caller was ' + myFunc.caller;
+  }
+}
+
+myFunc();
+// Warning: ReferenceError: deprecated caller usage
+// "The function was called from the top!"
+ +

Function.arguments

+ +

{{jsxref("Function.arguments")}} 已被废弃。 (详见参考文章)。

+ +
"use strict";
+
+function f(n) { g(n - 1); }
+
+function g(n) {
+  console.log('before: ' + g.arguments[0]);
+  if (n > 0) { f(n); }
+  console.log('after: ' + g.arguments[0]);
+}
+
+f(2);
+
+console.log('returned: ' + g.arguments);
+// Warning: ReferenceError: deprecated arguments usage
+
+ +

相关

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/deprecated_expression_closures/index.html b/files/zh-cn/web/javascript/reference/errors/deprecated_expression_closures/index.html new file mode 100644 index 0000000000..465bd6741b --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/deprecated_expression_closures/index.html @@ -0,0 +1,78 @@ +--- +title: 'Warning: expression closures are deprecated' +slug: Web/JavaScript/Reference/Errors/Deprecated_expression_closures +tags: + - JavaScript + - 警告 +translation_of: Web/JavaScript/Reference/Errors/Deprecated_expression_closures +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
Warning: expression closures are deprecated
+
+ +

错误类型

+ +

警告。JavaScript 引擎不会停止运行。

+ +

哪里出错了?

+ +

非标准化的表达式闭包语法(简写函数语法)已被废弃,不应该再被使用。该语法将会在 {{bug(1083458)}} 中全部移除,到时候用到该语法的脚本程序会报  SyntaxError 错误。

+ +

示例

+ +

被废弃的语法

+ +

表达式闭包从函数声明或者对象方法定义中省略了花括号或是 return 语句。

+ +
var x = function() 1;
+
+var obj = {
+  count: function() 1
+};
+
+ +

标准语法

+ +

将非标准化的表达式闭包语法转换成标准 ECMAScript 语法,可以添加花括号以及 return 语句。

+ +
var x = function() { return 1; }
+
+var obj = {
+  count: function() { return 1; }
+};
+
+ +

标准语法之箭头函数

+ +

另外,你可以选择使用箭头函数:

+ +
var x = () => 1;
+ +

标准语法之方法的简略写法

+ +

表达式闭包还会出现在 getter 与 setter 中,例如:

+ +
var obj = {
+  get x() 1,
+  set x(v) this.v = v
+};
+
+ +

根据 ES2015 中对于方法定义的规定,上述写法可以转换成如下形式:

+ +
var obj = {
+  get x() { return 1 },
+  set x(v) { this.v = v }
+};
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/deprecated_octal/index.html b/files/zh-cn/web/javascript/reference/errors/deprecated_octal/index.html new file mode 100644 index 0000000000..ca56bc00ac --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/deprecated_octal/index.html @@ -0,0 +1,67 @@ +--- +title: 'SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated' +slug: Web/JavaScript/Reference/Errors/Deprecated_octal +tags: + - JavaScript + - 严格模式 + - 语法错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Deprecated_octal +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
SyntaxError:
+"0"-prefixed octal literals and octal escape sequences are deprecated;
+for octal literals use the \"0o\" prefix instead
+
+ +

错误类型

+ +

语法错误({{jsxref("SyntaxError")}} ),只出现于严格模式下。

+ +

哪里出错了?

+ +

八进制字面量与八进制转义序列语法已经被废弃,在严格模式下会报语法错误({{jsxref("SyntaxError")}})。在 ECMAScript 2015 及以后的规范中,标准语法是前导 0 后面跟一个大写或小写的拉丁文字母 "O" (0o 或 0O)。

+ +

示例

+ +

前导"0"形式的八进制字面量

+ +
"use strict";
+
+03;
+
+// SyntaxError: "0"-prefixed octal literals and octal escape sequences
+// are deprecated
+ +

八进制转义序列

+ +
"use strict";
+
+"\251";
+
+// SyntaxError: "0"-prefixed octal literals and octal escape sequences
+// are deprecated
+
+ +

合法的八进制数字

+ +

使用前导 0 后面跟字母 "o" 或 "O" 的形式:

+ +
0o3;
+
+ +

至于八进制转义序列,你可以使用十六进制转义序列来代替:

+ +
'\xA9';
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/deprecated_source_map_pragma/index.html b/files/zh-cn/web/javascript/reference/errors/deprecated_source_map_pragma/index.html new file mode 100644 index 0000000000..e37aec2fa3 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/deprecated_source_map_pragma/index.html @@ -0,0 +1,109 @@ +--- +title: >- + SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# + instead +slug: Web/JavaScript/Reference/Errors/Deprecated_source_map_pragma +tags: + - Errors + - JavaScript + - Source maps +translation_of: Web/JavaScript/Reference/Errors/Deprecated_source_map_pragma +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
Warning: SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
+
+Warning: SyntaxError: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}} 的警告。不会终止 JavaScript 的执行。

+ +

哪里错了?

+ +

在 JavaScript 源码中使用了已废弃的 source map 语法。

+ +

JavaScript 源代码经常被组合和压缩,以便能更高效地从服务器获取它们。使用了 source maps,调试器就可以将正在执行的代码映射到原始源文件。

+ +

因为 IE 浏览器只要页面在 //@cc_on 之后的都会被IE JScript引擎解释为打开条件编译后,所以 source map 的规范更改了语法。条件编译注释 是 IE 的一个小特色,但是它破坏了 jQuery 和其他库的 source map。

+ +

示例

+ +

废弃的语法

+ +

使用 "@" 符号的语法已经被废弃了。

+ +
//@ sourceMappingURL=http://example.com/path/to/your/sourcemap.map
+
+ +

标准语法

+ +

使用 "#" 符号代替。

+ +
//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map
+ +

或者,您也可以为 JavaScript 文件设置 header,以避免添加注释:

+ +
X-SourceMap: /path/to/file.js.map
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
New syntax{{CompatVersionUnknown}}{{ CompatGeckoDesktop(24) }}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
New syntax{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile(24) }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/deprecated_string_generics/index.html b/files/zh-cn/web/javascript/reference/errors/deprecated_string_generics/index.html new file mode 100644 index 0000000000..dd59c26276 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/deprecated_string_generics/index.html @@ -0,0 +1,104 @@ +--- +title: 'Warning: String.x is deprecated; use String.prototype.x instead' +slug: Web/JavaScript/Reference/Errors/Deprecated_String_generics +tags: + - JavaScript + - 警告 +translation_of: Web/JavaScript/Reference/Errors/Deprecated_String_generics +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
Warning: String.charAt            is deprecated; use String.prototype.charAt            instead
+Warning: String.charCodeAt        is deprecated; use String.prototype.charCodeAt        instead
+Warning: String.concat            is deprecated; use String.prototype.concat            instead
+Warning: String.contains          is deprecated; use String.prototype.contains          instead
+Warning: String.endsWith          is deprecated; use String.prototype.endsWith          instead
+Warning: String.includes          is deprecated; use String.prototype.includes          instead
+Warning: String.indexOf           is deprecated; use String.prototype.indexOf           instead
+Warning: String.lastIndexOf       is deprecated; use String.prototype.lastIndexOf       instead
+Warning: String.localeCompare     is deprecated; use String.prototype.localeCompare     instead
+Warning: String.match             is deprecated; use String.prototype.match             instead
+Warning: String.normalize         is deprecated; use String.prototype.normalize         instead
+Warning: String.replace           is deprecated; use String.prototype.replace           instead
+Warning: String.search            is deprecated; use String.prototype.search            instead
+Warning: String.slice             is deprecated; use String.prototype.slice             instead
+Warning: String.split             is deprecated; use String.prototype.split             instead
+Warning: String.startsWith        is deprecated; use String.prototype.startsWith        instead
+Warning: String.substr            is deprecated; use String.prototype.substr            instead
+Warning: String.substring         is deprecated; use String.prototype.substring         instead
+Warning: String.toLocaleLowerCase is deprecated; use String.prototype.toLocaleLowerCase instead
+Warning: String.toLocaleUpperCase is deprecated; use String.prototype.toLocaleUpperCase instead
+Warning: String.toLowerCase       is deprecated; use String.prototype.toLowerCase       instead
+Warning: String.toUpperCase       is deprecated; use String.prototype.toUpperCase       instead
+Warning: String.trim              is deprecated; use String.prototype.trim              instead
+Warning: String.trimLeft          is deprecated; use String.prototype.trimLeft          instead
+Warning: String.trimRight         is deprecated; use String.prototype.trimRight         instead
+
+ +

错误类型

+ +

警告。JavaScript 引擎不会停止运行。

+ +

哪里出错了?

+ +

非标准的泛型  {{jsxref("String")}} 方法已经被废弃,将来会被移除(这些方法仅在 Firefox 浏览器中得到实现)。String 泛型在 String 对象上提供了一系列的 String 实例方法,使得这些 String 方法可以应用于任何类型的对象。

+ +

Firefox {{bug(1222552)}} 对 String 泛型方法的移除进行了追踪。

+ +

示例

+ +

废弃的语法

+ +
var num = 15;
+String.replace(num, /5/, '2');
+ +

标准语法

+ +
var num = 15;
+String(num).replace(/5/, '2');
+
+ +

垫片

+ +

以下是一个垫片脚本来为不支持 String 泛型方法浏览器提供支持:

+ +
/*globals define*/
+// Assumes all supplied String instance methods already present
+// (one may use shims for these if not available)
+(function() {
+  'use strict';
+
+  var i,
+    // We could also build the array of methods with the following, but the
+    //   getOwnPropertyNames() method is non-shimable:
+    // Object.getOwnPropertyNames(String).filter(function(methodName) {
+    //   return typeof String[methodName] === 'function';
+    // });
+    methods = [
+      'contains', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
+      'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
+      'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase', 'normalize',
+      'toLocaleUpperCase', 'localeCompare', 'match', 'search', 'slice',
+      'replace', 'split', 'substr', 'concat', 'localeCompare'
+    ],
+    methodCount = methods.length,
+    assignStringGeneric = function(methodName) {
+      var method = String.prototype[methodName];
+      String[methodName] = function(arg1) {
+        return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
+      };
+    };
+
+  for (i = 0; i < methodCount; i++) {
+    assignStringGeneric(methods[i]);
+  }
+}());
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/deprecated_tolocaleformat/index.html b/files/zh-cn/web/javascript/reference/errors/deprecated_tolocaleformat/index.html new file mode 100644 index 0000000000..e8e8040227 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/deprecated_tolocaleformat/index.html @@ -0,0 +1,90 @@ +--- +title: 'Warning: Date.prototype.toLocaleFormat is deprecated' +slug: Web/JavaScript/Reference/Errors/Deprecated_toLocaleFormat +tags: + - JavaScript + - 警告 +translation_of: Web/JavaScript/Reference/Errors/Deprecated_toLocaleFormat +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
Warning: Date.prototype.toLocaleFormat is deprecated; consider using Intl.DateTimeFormat instead
+
+ +

错误类型

+ +

警告。JavaScript 引擎不会停止运行。

+ +

哪里出错了?

+ +

{{jsxref("Date.prototype.toLocaleFormat")}} 是非标准化的方法,已经被废弃,不应该再进行使用。该方法需要传入与 C 语言中的strftime() 方法相似的格式化字符串。该实现将会在 {{bug(818634)}} 中完全移除。

+ +

示例

+ +

废止使用的语法

+ +

{{jsxref("Date.prototype.toLocaleFormat")}} 方法已经废弃,以后会被移除(只在 Firefox 浏览器中有用到,没有在其他浏览器中使用)。

+ +
var today = new Date();
+var date = today.toLocaleFormat('%A, %e. %B %Y');
+
+console.log(date);
+// In German locale
+// "Freitag, 10. März 2017"
+ +

备选标准语法之一:使用 ECMAScript Intl API 

+ +

ECMA-402 (ECMAScript Intl API) 标准规定了支持不同语言的日期和时间格式化形式的对象和方法(在 Chrome 24+, Firefox 29+, IE11+, Safari10+ 中可用)。

+ +

现在如果只需要格式化一个日期对象的话,那么可以使用 {{jsxref("Date.prototype.toLocaleDateString")}} 方法。

+ +
var today = new Date();
+var options = { weekday: 'long', year: 'numeric',
+                month: 'long', day: 'numeric' };
+var date = today.toLocaleDateString('de-DE', options);
+
+console.log(date);
+// "Freitag, 10. März 2017"
+
+ +

或者,可以使用 {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} 对象,该对象允许你将格式化器对象缓存起来,省去很多重复性的计算工作,所以格式化操作会很快。这在需要对一系列的日期对象进行格式化的时候非常有用。

+ +
var options = { weekday: 'long', year: 'numeric',
+                month: 'long', day: 'numeric' };
+var dateFormatter = new Intl.DateTimeFormat('de-DE', options)
+
+var dates = [Date.UTC(2012, 11, 20, 3, 0, 0),
+             Date.UTC(2014, 04, 12, 8, 0, 0)];
+
+dates.forEach(date => console.log(dateFormatter.format(date)));
+
+// "Donnerstag, 20. Dezember 2012"
+// "Montag, 12. Mai 2014"
+
+ +

备选标准语法之二:使用 Date 对象的方法

+ +

{{jsxref("Date")}} 对象提供了一系列的方法来生成定制化的格式化字符串。

+ +
(new Date()).toLocaleFormat("%Y%m%d");
+// "20170310"
+
+ +

可以转换为:

+ +
let now = new Date();
+let date = now.getFullYear() * 10000 +
+          (now.getMonth() + 1) * 100 + now.getDate();
+
+console.log(date);
+// "20170310"
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/equal_as_assign/index.html b/files/zh-cn/web/javascript/reference/errors/equal_as_assign/index.html new file mode 100644 index 0000000000..e92f0a63e8 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/equal_as_assign/index.html @@ -0,0 +1,52 @@ +--- +title: 'SyntaxError: test for equality (==) mistyped as assignment (=)?' +slug: Web/JavaScript/Reference/Errors/Equal_as_assign +tags: + - 语法错误 +translation_of: Web/JavaScript/Reference/Errors/Equal_as_assign +--- +
{{jsSidebar("Errors")}}
+ +

消息

+ +
Warning: SyntaxError: test for equality (==) mistyped as assignment (=)?
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}} 只在严格模式下会出现的警告。

+ +

什么地方出错了?

+ +

在通常期望进行相等判定(==)的地方出现了赋值(=)。 为了帮助调试,JavaScript(在开启严格模式的情况下)会对这种情况进行警告。

+ +

示例

+ +

条件表达式内的赋值

+ +

不建议在条件表达式中 (例如 if...else) 使用简单赋值语句,因为在扫视代码的时候赋值操作与相等判定容易产生混淆。例如,不要使用以下写法:

+ +
if (x = y) {
+  // do the right thing
+}
+
+ +

如果你需要在条件表达式中使用赋值语句, 通常的做法是用一对括号把赋值语句包起来。 例如:

+ +
if ((x = y)) {
+  // do the right thing
+}
+ +

否则, 你的本意可能是想用比较操作符 (如 =====):

+ +
if (x == y) {
+  // do the right thing
+}
+ +

相关页面

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/for-each-in_loops_are_deprecated/index.html b/files/zh-cn/web/javascript/reference/errors/for-each-in_loops_are_deprecated/index.html new file mode 100644 index 0000000000..351be47a9d --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/for-each-in_loops_are_deprecated/index.html @@ -0,0 +1,171 @@ +--- +title: 'Warning: JavaScript 1.6''s for-each-in loops are deprecated' +slug: Web/JavaScript/Reference/Errors/For-each-in_loops_are_deprecated +tags: + - Warning +translation_of: Web/JavaScript/Reference/Errors/For-each-in_loops_are_deprecated +--- +
{{jsSidebar("Errors")}}
+ +

消息

+ +
警告: JavaScript 1.6's 版本的for-each-in遍历不再赞成使用; 建议用 ES6的 for-of 替换
+
+ +

错误类型

+ +

警告

+ +

出了什么问题?

+ +

JavaScript 1.6's {{jsxref("Statements/for_each...in", "for each (variable in obj)")}}语法不赞成使用, 将在未来版本移除它。

+ +

实例

+ +

遍历对象

+ +

{{jsxref("Statements/for_each...in", "for each...in")}} 用来遍历指定对象.

+ +

不赞成这么使用

+ +
+

var object = { a: 10, b: 20 };

+ +

for each (var x in object) {
+   console.log(x);        // 10
+                          // 20
+ }

+
+ +

替换语法

+ +

你可以使用 {{jsxref("Statements/for...in", "for...in")}} 遍历指定对象, 获取每次循环的值:

+ +
var object = { a: 10, b: 20 };
+
+for (var key in object) {
+  var x = object[key];
+  console.log(x);        // 10
+                         // 20
+}
+
+ +

也可以使用{jsxref("Statements/for...of", "for...of")}} (ES2015) 和 {{jsxref("Object.values")}} (ES2017), 你可以获取指定对象的值得数组然后像这样遍历它:

+ +
var object = { a: 10, b: 20 };
+
+for (var x of Object.values(object)) {
+  console.log(x);        // 10
+                         // 20
+}
+
+ +

数组遍历

+ +

{{jsxref("Statements/for_each...in", "for each...in")}} 被用于遍历制定数组.

+ +

不赞成这么使用

+ +
+

var array = [10, 20, 30];

+ +

for each (var x in array) {
+   console.log(x);        // 10
+                          // 20
+                          // 30
+ }

+
+ +

替换语法

+ +

现在最好用{{jsxref("Statements/for...of", "for...of")}} (ES2015) 替换

+ +
var array = [10, 20, 30];
+
+for (var x of array) {
+  console.log(x);        // 10
+                         // 20
+                         // 30
+}
+
+ +

遍历一个空数组

+ +

{{jsxref("Statements/for_each...in", "for each...in")}} 如果指定值是 null o或 undefined什么都遍历不出来。 {{jsxref("Statements/for...of", "for...of")}} 在这种情况会抛出异常.

+ +

不赞成这么使用

+ +
+

function func(array) {
+   for each (var x in array) {
+     console.log(x);
+   }
+ }
+ func([10, 20]);        // 10
+                        // 20
+ func(null);            // prints nothing
+ func(undefined);       // prints nothing

+
+ +

替换语法

+ +

用{{jsxref("Statements/for...of", "for...of")}} 重写{{jsxref("Statements/for_each...in", "for each...in")}} 后值可以为 null 和 undefined  ,同时你需要警惕{{jsxref("Statements/for...of", "for...of")}}抛出的异常.

+ +
function func(array) {
+  if (array) {
+    for (var x of array) {
+      console.log(x);
+    }
+  }
+}
+func([10, 20]);        // 10
+                       // 20
+func(null);            // prints nothing
+func(undefined);       // prints nothing
+
+ +

遍历对象键值对

+ +

不赞成这么使用

+ +

 不赞成使用{{jsxref("Statements/for_each...in", "for each...in")}}和{{jsxref("Iterator")}} 对象来遍历指定对象的键值对.

+ +
+

var object = { a: 10, b: 20 };

+ +

for each (var [key, value] in Iterator(object)) {
+   console.log(key, value);  // "a", 10
+                             // "b", 20
+ }

+
+ +

替换语法

+ +

你可以使用 {{jsxref("Statements/for...in", "for...in")}} 遍历指定对象,获取每次循环的值:

+ +
var object = { a: 10, b: 20 };
+
+for (var key in object) {
+  var value = object[key];
+  console.log(key, value);  // "a", 10
+                            // "b", 20
+}
+
+ +

也可以使用{jsxref("Statements/for...of", "for...of")}} (ES2015) 和 {{jsxref("Object.values")}} (ES2017), 你可以获取指定对象的值得数组然后像这样遍历它:

+ +
var object = { a: 10, b: 20 };
+
+for (var [key, value] of Object.entries(object)) {
+  console.log(key, value);  // "a", 10
+                            // "b", 20
+}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/getter_only/index.html b/files/zh-cn/web/javascript/reference/errors/getter_only/index.html new file mode 100644 index 0000000000..0636f30eea --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/getter_only/index.html @@ -0,0 +1,82 @@ +--- +title: 'TypeError: setting getter-only property "x"' +slug: Web/JavaScript/Reference/Errors/Getter_only +tags: + - JavaScript + - 严格模式 + - 类型错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Getter_only +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
TypeError: setting getter-only property "x" (Firefox)
+TypeError: Cannot set property "prop" of #<Object> which has only a getter (Chrome)
+
+ +

错误类型

+ +

仅在严格模式下报 {{jsxref("TypeError")}} 错误。

+ +

哪里出错了?

+ +

该错误提示出现于试图给一个仅仅设置了 getter 特性的属性赋新值的时候。在非严格模式下会被静默忽略,而在严格模式下会报 {{jsxref("TypeError")}} 错误。

+ +

示例

+ +

下面的例子展示了如何为一个属性设置 getter 特性。由于没有设置 setter 特性,所以在试图将 temperature 属性值设置为 30 的时候会报 TypeError 的错误。相关细节信息可以参考 {{jsxref("Object.defineProperty()")}} 页面。

+ +
"use strict";
+
+function Archiver() {
+  var temperature = null;
+  Object.defineProperty(this, 'temperature', {
+    get: function() {
+      console.log('get!');
+      return temperature;
+    }
+  });
+}
+
+var arc = new Archiver();
+arc.temperature; // 'get!'
+
+arc.temperature = 30;
+// TypeError: setting getter-only property "temperature"
+ +

至于修复问题的方法,可以将第 16 行的代码移除,因为它试图为 temperature 属性赋值,或者是为它添加一个 setter 特性,就像下面这样:

+ +
"use strict";
+
+function Archiver() {
+  var temperature = null;
+  var archive = [];
+
+  Object.defineProperty(this, 'temperature', {
+    get: function() {
+      console.log('get!');
+      return temperature;
+    },
+    set: function(value) {
+      temperature = value;
+      archive.push({ val: temperature });
+    }
+  });
+
+  this.getArchive = function() { return archive; };
+}
+
+var arc = new Archiver();
+arc.temperature; // 'get!'
+arc.temperature = 11;
+arc.temperature = 13;
+arc.getArchive(); // [{ val: 11 }, { val: 13 }]
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/identifier_after_number/index.html b/files/zh-cn/web/javascript/reference/errors/identifier_after_number/index.html new file mode 100644 index 0000000000..c2607edd2b --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/identifier_after_number/index.html @@ -0,0 +1,48 @@ +--- +title: 'SyntaxError: identifier starts immediately after numeric literal' +slug: Web/JavaScript/Reference/Errors/Identifier_after_number +translation_of: Web/JavaScript/Reference/Errors/Identifier_after_number +--- +
{{JSSidebar("Errors")}}
+ +

Message

+ +
SyntaxError: identifier starts immediately after numeric literal (Firefox)
+SyntaxError: Unexpected number (Chrome)
+
+ +

Error type

+ +

{{jsxref("SyntaxError")}}

+ +

What went wrong?

+ +

变量名叫{{Glossary("Identifier", "identifiers")}},它符合某些规则,而你打破了这些规则!

+ +

一个JavaScript标识符必须以字母开头,下划线(_)或美元符号($)。他们不能以数字开头。只有后续字符可以是数字(0-9)。

+ +

Examples

+ +

Variable names starting with numeric literals

+ +

Variable names can't start with numbers in JavaScript. The following fails:

+ +
var 1life = 'foo';
+// SyntaxError: identifier starts immediately after numeric literal
+
+var foo = 1life;
+// SyntaxError: identifier starts immediately after numeric literal
+
+ +

You will need to rename your variable to avoid the leading number.

+ +
var life1 = 'foo';
+var foo = life1;
+
+ +

See also

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/illegal_character/index.html b/files/zh-cn/web/javascript/reference/errors/illegal_character/index.html new file mode 100644 index 0000000000..16367c43a2 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/illegal_character/index.html @@ -0,0 +1,73 @@ +--- +title: 'SyntaxError: illegal character' +slug: Web/JavaScript/Reference/Errors/Illegal_character +tags: + - JavaScript + - 语法错误 +translation_of: Web/JavaScript/Reference/Errors/Illegal_character +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
SyntaxError: illegal character (Firefox)
+SyntaxError: Invalid or unexpected token (Chrome)
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

在代码中有非法的或者不期望出现的标记符号出现在不该出现的位置。请使用支持语法高亮功能的编辑器仔细检查你的代码,看看是否存在张冠李戴的情况,比如减号 ( - ) 与连接符 () ,或者是英文双引号 ( " ) 与中文双引号 ()。

+ +

示例

+ +

错配字符

+ +

一些字符看起来会很相像,但是会导致于语法解析器解析代码失败。

+ +
“This looks like a string”;
+// SyntaxError: illegal character
+
+42 – 13;
+// SyntaxError: illegal character
+
+ +

下面这样是可以正常运行的:

+ +
"This is actually a string";
+
+42 - 13;
+
+ +

遗漏的字符

+ +

很容易就会在这里或那里遗漏一些字符。

+ +
var colors = ['#000', #333', '#666'];
+// SyntaxError: illegal character
+
+ +

把遗漏的引号给 '#333' 添加上。

+ +
var colors = ['#000', '#333', '#666'];
+ +

隐藏字符

+ +

当从外部复制粘贴代码的时候,有可能就有非法的隐藏字符的存在,需要引起注意!

+ +
var foo = 'bar';​
+// SyntaxError: illegal character
+
+ +

当使用文本编辑器如VIM进行探测的时候,可以发现这里存在一个零宽空格 (ZWSP) (U+200B) 。

+ +
var foo = 'bar';​<200b>
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/in_operator_no_object/index.html b/files/zh-cn/web/javascript/reference/errors/in_operator_no_object/index.html new file mode 100644 index 0000000000..fa607780a7 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/in_operator_no_object/index.html @@ -0,0 +1,71 @@ +--- +title: 'TypeError: invalid ''in'' operand "x"' +slug: Web/JavaScript/Reference/Errors/in_operator_no_object +tags: + - JavaScript + - 类型错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/in_operator_no_object +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
TypeError: invalid 'in' operand "x" (Firefox)
+TypeError: Cannot use 'in' operator to search for 'x' in y (Chrome)
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

in 操作符只可以用来检测对象中是否存在某个属性,而不能用来在字符串、数字或者其他基本类型的数据中进行检索。

+ +

示例

+ +

在字符串中进行检索

+ +

与其他语言不同(如 Python),不能使用 in 操作符在字符串中进行检索。

+ +
"Hello" in "Hello World";
+// TypeError: invalid 'in' operand "Hello World"
+
+ +

可以使用 {{jsxref("String.prototype.indexOf()")}} 来代替:

+ +
"Hello World".indexOf("Hello") !== -1;
+// true
+ +

操作数不能为 null 或者 undefined

+ +

确保你将要进行探测的对象不为 {{jsxref("null")}} 或者  {{jsxref("undefined")}}.

+ +
var foo = null;
+"bar" in foo;
+// TypeError: invalid 'in' operand "foo"
+
+ +

in 操作符的预期操作数只有对象类型。

+ +
var foo = { baz: "bar" };
+"bar" in foo; // false
+
+"PI" in Math; // true
+"pi" in Math; // false
+
+ +

在数组中进行检索

+ +

当使用 in 操作符来对 {{jsxref("Array")}} 对象进行检索的时候一定要特别小心,因为它检测的是索引值而不是位于索引位置的值。

+ +
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
+3 in trees; // true
+"oak" in trees; // false
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/index.html b/files/zh-cn/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..f0c0f2560a --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/index.html @@ -0,0 +1,28 @@ +--- +title: JavaScript 错误参考 +slug: Web/JavaScript/Reference/Errors +tags: + - Debugging + - Errors + - JavaScript + - 调试 + - 错误 +translation_of: Web/JavaScript/Reference/Errors +--- +

{{jsSidebar("Errors")}}

+ +

下面列出了 JavaScript 抛出的错误。这些错误是有用的调试帮助,但报告的问题并不总是十分明了。下面的页面提供有关这些错误的详细信息。每个错误都是基于 {{jsxref("Error")}}  的对象,并且具有名称和消息。

+ +

Web 控制台中显示的错误可能包含指向下面相应页面的链接,以帮助您快速理解代码中的问题。

+ +

错误列表

+ +

在此列表中,每个页面按名称(错误类型)和信息(更详细的容易理解的错误信息)列出。 总之,这两者提供了理解和解决错误的线索。 有关更多信息,请按照以下链接!

+ +

{{ListSubPages("/zh-CN/docs/Web/JavaScript/Reference/Errors")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/invalid_array_length/index.html b/files/zh-cn/web/javascript/reference/errors/invalid_array_length/index.html new file mode 100644 index 0000000000..6e74db20b8 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/invalid_array_length/index.html @@ -0,0 +1,77 @@ +--- +title: 'RangeError: invalid array length' +slug: Web/JavaScript/Reference/Errors/Invalid_array_length +tags: + - JavaScript + - 范围错误 + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length +--- +
{{jsSidebar("Errors")}}
+ +

错误信息

+ +
RangeError: invalid array length (Firefox)
+RangeError: Invalid array length (Chrome)
+RangeError: Invalid array buffer length (Chrome)
+
+ +

错误类型

+ +

{{jsxref("RangeError")}}

+ +

什么地方出错了?

+ +

无效的数组错误长度通常会在以下情形中出现:

+ + + +

为什么 Array(数组) 和 ArrayBuffer(数组缓冲区) 的长度会受到限制?因为 Array 和 ArrayBuffer 的 length(长度) 属性被定义为一个32位无符号整形(unsigned 32-bit integer)的值,所以它只能存储 0 - 232-1 之间的数。

+ +

当你使用构造函数来创建一个数组的时候,你可能想使用字面值的形式,第一个参数会被解释为数组的长度。

+ +

或者说,你想要在设置数组之前确定它的长度,或把它作为一个构造函数的参数。

+ +

示例

+ +

错误的示例

+ +
new Array(Math.pow(2, 40))
+new Array(-1)
+new ArrayBuffer(Math.pow(2, 32))
+new ArrayBuffer(-1)
+
+let a = [];
+a.length = a.length - 1;         // 将 length 属性的值设置为 -1
+
+let b = new Array(Math.pow(2, 32) - 1);
+b.length = b.length + 1;         // 将 length 属性的值设置为 2^32
+
+ +

正确的示例

+ +
[ Math.pow(2, 40) ]                     // [ 1099511627776 ]
+[ -1 ]                                  // [ -1 ]
+new ArrayBuffer(Math.pow(2, 32) - 1)
+new ArrayBuffer(0)
+
+let a = [];
+a.length = Math.max(0, a.length - 1);
+
+let b = new Array(Math.pow(2, 32) - 1);
+b.length = Math.min(0xffffffff, b.length + 1);
+
+// 0xffffffff 是 2^32 - 1 的 十六进制 表示方式
+// 它也可以被写作 (-1 >>> 0)
+
+ +

相关页面

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html b/files/zh-cn/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html new file mode 100644 index 0000000000..e3506fc199 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html @@ -0,0 +1,54 @@ +--- +title: 'ReferenceError: invalid assignment left-hand side' +slug: Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side +tags: + - Errors + - JavaScript + - ReferenceError +translation_of: Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side +--- +
{{jsSidebar("Errors")}}
+ +

Message

+ +
ReferenceError: invalid assignment left-hand side
+
+ +

Error type

+ +

{{jsxref("ReferenceError")}}.

+ +

What went wrong?

+ +

有时会出现不可预料的赋值情况。这可能是因为赋值运算符比较运算符不匹配的缘故。正确的是,使用“=”号将值赋给一个变量,使用“==”或者“===”来比较一个值。

+ +

Examples

+ +
if (Math.PI = 3 || Math.PI = 4) {
+  console.log('no way!');
+}
+// ReferenceError: invalid assignment left-hand side
+
+var str = 'Hello, '
++= 'is it me '
++= 'you\'re looking for?';
+// ReferenceError: invalid assignment left-hand side
+
+ +

if 语句中,你要使用比较运算符("=="),而在字符串连接中,使用加号运算符("+")。

+ +
if (Math.PI == 3 || Math.PI == 4) {
+  console.log('no way!');
+}
+
+var str = 'Hello, '
++ 'from the '
++ 'other side!';
+
+ +

See also

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/invalid_const_assignment/index.html b/files/zh-cn/web/javascript/reference/errors/invalid_const_assignment/index.html new file mode 100644 index 0000000000..330bab78c8 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/invalid_const_assignment/index.html @@ -0,0 +1,90 @@ +--- +title: 'TypeError: invalid assignment to const "x"' +slug: Web/JavaScript/Reference/Errors/Invalid_const_assignment +tags: + - JavaScript + - 类型错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Invalid_const_assignment +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
TypeError: invalid assignment to const "x" (Firefox)
+TypeError: Assignment to constant variable. (Chrome)
+TypeError: Redeclaration of const 'x' (IE/Edge)
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

常量指的是无法在程序正常运行过程中进行修改的值。一方面无法通过重新赋值进行修改,另外一方面也无法进行重新声明。在 JavaScript 中,常量通过关键字 const 来声明。

+ +

示例

+ +

不合法的二次声明

+ +

在同一作用域内为相同的常量名进行赋值会报错。

+ +
const COLUMNS = 80;
+
+// ...
+
+COLUMNS = 120; // TypeError: invalid assignment to const `COLUMNS'
+ +

问题修复

+ +

修复的方式有很多种。可以根据你想要达到的目的来有针对性地对其进行处理。

+ +

重新命名

+ +

如果想要声明另一个变量,那么请选择其他名称对其重新命名。原来的常量名在该作用域中已经被占有。

+ +
const COLUMNS = 80;
+const WIDE_COLUMNS = 120;
+ +

const, let or var?

+ +

如果你的目的不是为了创建一个常量的话,那么就不要使用 const 关键字。可以使用 let 关键字来声明一个拥有块作用域的变量,或者使用 var 来声明一个全局变量。

+ +
let columns = 80;
+
+// ...
+
+let columns = 120;
+
+ +

作用域

+ +

检查一下作用域是否正确。例如这个常量是否应该出现在当前作用域,还是应该出现在函数内部?

+ +
const COLUMNS = 80;
+
+function setupBigScreenEnvironment() {
+  const COLUMNS = 120;
+}
+ +

const与不可变性

+ +

const 声明语句创建了一个对值的只读引用。这并意味着它指向的值是不可变的,而是说这个变量标记符不能被再次分配。例如,在值是对象的情况下,引用的对象自身内容依然是可以改变的。不能改变该变量的引用:

+ +
const obj = {foo: 'bar'};
+obj = {foo: 'baz'}; // TypeError: invalid assignment to const `obj'
+
+ +

但是可以改变它引用的值的属性: 

+ +
obj.foo = 'baz';
+obj; // Object { foo: "baz" }
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/invalid_date/index.html b/files/zh-cn/web/javascript/reference/errors/invalid_date/index.html new file mode 100644 index 0000000000..1deee46fcc --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/invalid_date/index.html @@ -0,0 +1,54 @@ +--- +title: 'RangeError: invalid date' +slug: Web/JavaScript/Reference/Errors/Invalid_date +tags: + - JavaScript + - 范围错误 + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Invalid_date +--- +
{{jsSidebar("Errors")}}
+ +

消息

+ +
范围错误: 非法数据(Firefox)
+范围错误: 非法时间值 (Chrome)
+范围错误: 提供的数据不是有效的 (Chrome)
+
+ +

错误类型

+ +

{{jsxref("RangeError")}}

+ +

哪里出错了?

+ +

为 {{jsxref("Date")}} 或 {{jsxref("Date.parse()")}} 提供了一个会导致无效日期的字符串。

+ +

示例

+ +

错误示例

+ +

ISO格式化字符串中不可识别的字符串或者包含非法元素值的日期一般会返回 {{jsxref("NaN")}}。然而,根据实现的不同,不符合ISO格式的字符串可能也会抛出 RangeError: invalid date,比如在火狐浏览器中有以下情形:

+ +
new Date('foo-bar 2014');
+new Date('2014-25-23').toISOString();
+new Date('foo-bar 2014').toString();
+
+ +

然而下面这种情形会返回 {{jsxref("NaN")}} :

+ +
Date.parse('foo-bar 2014'); // NaN
+ +

参见 {{jsxref("Date.parse()")}} 文档,了解更多详情。

+ +

正确示例

+ +
new Date('05 October 2011 14:48 UTC');
+ +

另见

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/invalid_for-in_initializer/index.html b/files/zh-cn/web/javascript/reference/errors/invalid_for-in_initializer/index.html new file mode 100644 index 0000000000..34dcefa8ed --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/invalid_for-in_initializer/index.html @@ -0,0 +1,73 @@ +--- +title: 'SyntaxError: for-in loop head declarations may not have initializers' +slug: Web/JavaScript/Reference/Errors/Invalid_for-in_initializer +tags: + - JavaScript + - 严格模式 + - 语法错误 +translation_of: Web/JavaScript/Reference/Errors/Invalid_for-in_initializer +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
SyntaxError: for-in loop head declarations may not have initializers (Firefox)
+
+SyntaxError: for-in loop variable declaration may not have an initializer. (Chrome)
+
+ +

错误类型

+ +

该 {{jsxref("SyntaxError")}} 只出现于严格模式下。

+ +

哪里出错了?

+ +

在 for...in 循环的头部存在初始化表达式。 也就是存在变量声明并且被赋值,例如 |for (var i = 0 in obj)|。在非严格模式下,这种在循环头部的变量声明会被静默忽略,语句的表现形式与 |for (var i in obj)|相同。而在严格模式下,会报语法错误。

+ +

示例

+ +

下面这个示例会报语法错误(SyntaxError):

+ +
"use strict";
+
+var obj = {a: 1, b: 2, c: 3 };
+
+for (var i = 0 in obj) {
+  console.log(obj[i]);
+}
+
+// SyntaxError: for-in loop head declarations may not have initializers
+
+ +

合法的 for-in 循环

+ +

可以把初始化语句 (i = 0) 从 for-in 循环的头部移除。

+ +
"use strict";
+
+var obj = {a: 1, b: 2, c: 3 };
+
+for (var i in obj) {
+  console.log(obj[i]);
+}
+
+ +

数组迭代

+ +

for...in 循环不应该应用于数组迭代中。是否考虑使用 for 循环而不是 for-in 循环来遍历数组({{jsxref("Array")}})?在 for 循环中是允许使用初始化语句的:

+ +
var arr = [ "a", "b", "c" ]
+
+for (var i = 2; i < arr.length; i++) {
+  console.log(arr[i]);
+}
+
+// "c"
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/invalid_for-of_initializer/index.html b/files/zh-cn/web/javascript/reference/errors/invalid_for-of_initializer/index.html new file mode 100644 index 0000000000..7e93d3af35 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/invalid_for-of_initializer/index.html @@ -0,0 +1,63 @@ +--- +title: >- + SyntaxError: a declaration in the head of a for-of loop can't have an + initializer +slug: Web/JavaScript/Reference/Errors/Invalid_for-of_initializer +tags: + - JavaScript + - 语法错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Invalid_for-of_initializer +--- +
{{jsSidebar("Errors")}}
+ +

错误信息

+ +
SyntaxError: a declaration in the head of a for-of loop can't have an initializer (Firefox)
+
+SyntaxError: for-of loop variable declaration may not have an initializer. (Chrome)
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

for...of 循环的头部包含有初始化表达式。也就是对一个变量进行声明并赋值|for (var i = 0 of iterable)|。这在 for-of 循环中是被禁止的。你想要的可能是允许包含初始化器的 for 循环形式。

+ +

示例

+ +

非法的 for-of 循环形式

+ +
let iterable = [10, 20, 30];
+
+for (let value = 50 of iterable) {
+  console.log(value);
+}
+
+// SyntaxError: a declaration in the head of a for-of loop can't
+// have an initializer
+ +

合法的 for-of 循环形式

+ +

需要将初始化器 (value = 50) 从for-of 循环的头部移除。或许你的本意是给每个值添加 50 的偏移量,在这种情况下,可以在循环体中进行添加。

+ +
let iterable = [10, 20, 30];
+
+for (let value of iterable) {
+  value += 50;
+  console.log(value);
+}
+// 60
+// 70
+// 80
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/invalid_right_hand_side_instanceof_operand/index.html b/files/zh-cn/web/javascript/reference/errors/invalid_right_hand_side_instanceof_operand/index.html new file mode 100644 index 0000000000..2ce2214034 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/invalid_right_hand_side_instanceof_operand/index.html @@ -0,0 +1,56 @@ +--- +title: 'TypeError: invalid ''instanceof'' operand ''x''' +slug: Web/JavaScript/Reference/Errors/invalid_right_hand_side_instanceof_operand +translation_of: Web/JavaScript/Reference/Errors/invalid_right_hand_side_instanceof_operand +--- +
{{jsSidebar("Errors")}}
+ +

消息

+ +
TypeError: invalid 'instanceof' operand "x" (Firefox)
+TypeError: "x" is not a function (Firefox)
+TypeError: Right-hand side of 'instanceof' is not an object (Chrome)
+TypeError: Right-hand side of 'instanceof' is not callable (Chrome)
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

instanceof 操作符 希望右边的操作数为一个构造对象,即一个有 prototype 属性且可以调用的对象。

+ +

例子

+ +
"test" instanceof ""; // TypeError: invalid 'instanceof' operand ""
+42 instanceof 0;      // TypeError: invalid 'instanceof' operand 0
+
+function Foo() {}
+var f = Foo();        // Foo() is called and returns undefined
+var x = new Foo();
+
+x instanceof f;       // TypeError: invalid 'instanceof' operand f
+x instanceof x;       // TypeError: x is not a function
+
+ +

为了解决上述问题, 你可能需要将instanceof 操作符 换成 typeof 操作符, 或者确保你使用的是函数名称,而不是函数计算的结果。

+ +
typeof "test" == "string"; // true
+typeof 42 == "number"      // true
+
+function Foo() {}
+var f = Foo;               // Do not call Foo.
+var x = new Foo();
+
+x instanceof f;            // true
+x instanceof Foo;          // true
+
+ +

参见

+ + + +

 

diff --git a/files/zh-cn/web/javascript/reference/errors/is_not_iterable/index.html b/files/zh-cn/web/javascript/reference/errors/is_not_iterable/index.html new file mode 100644 index 0000000000..a3cd34eb82 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/is_not_iterable/index.html @@ -0,0 +1,126 @@ +--- +title: 'TypeError: ''x'' is not iterable' +slug: Web/JavaScript/Reference/Errors/is_not_iterable +tags: + - 生成器 + - 迭代器 +translation_of: Web/JavaScript/Reference/Errors/is_not_iterable +--- +
{{jsSidebar("Errors")}}
+ +

错误信息

+ +
TypeError: 'x' is not iterable (Firefox, Chrome)
+TypeError: 'x' is not a function or its return value is not iterable (Chrome)
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

发生了什么错误?

+ +

这个值作为 for…of  的表达式右值,或者作为一个函数的参数,如 {{jsxref("Promise.all")}} 或者 {{jsxref("TypedArray.from")}}, 不是一个 可迭代对象.  一个可迭代对象可以是一个内置可迭代类型,如{{jsxref("Array")}}, {{jsxref("String")}} 或 {{jsxref("Map")}}, 一个 generator 生成结果, 或者一个实现了 可迭代协议 的对象

+ +

示例

+ +

Iterating over Object properties

+ +

在JavaScript中, {{jsxref("Object")}} 是不可迭代的,除非它们实现了迭代协议. 因此, 你不能使用 for…of 来迭代对象的属性.

+ +
var obj = { 'France': 'Paris', 'England': 'London' };
+for (let p of obj) { // TypeError: obj is not iterable
+    // …
+}
+
+ +

做为替代你必须使用 {{jsxref("Object.keys")}} 或 {{jsxref("Object.entries")}} 来迭代对象的属性或属性值.

+ +
var obj = { 'France': 'Paris', 'England': 'London' };
+// 迭代属性名称:
+for (let country of Object.keys(obj)) {
+    var capital = obj[country];
+    console.log(country, capital);
+}
+
+for (const [country, capital] of Object.entries(obj))
+    console.log(country, capital);
+
+ +

这次case的另外一个选择是使用 {{jsxref("Map")}}:

+ +
var map = new Map;
+map.set('France', 'Paris');
+map.set('England', 'London');
+// Iterate over the property names:
+for (let country of map.keys()) {
+    let capital = map[country];
+    console.log(country, capital);
+}
+
+for (let capital of map.values())
+    console.log(capital);
+
+for (const [country, capital] of map.entries())
+    console.log(country, capital);
+
+ +

Iterating over a generator

+ +

Generators 是用来生成可迭代对象的函数.

+ +
function* generate(a, b) {
+  yield a;
+  yield b;
+}
+
+for (let x of generate) // TypeError: generate is not iterable
+    console.log(x);
+
+ +

当它没有被调用, 这个 {{jsxref("Function")}} 相应的是可调用的,但是不可迭代。 调用 generator 生成一个可迭代对象,该对象将迭代在生成器执行期间生成的值.

+ +
function* generate(a, b) {
+    yield a;
+    yield b;
+}
+
+for (let x of generate(1,2))
+    console.log(x);
+ +

Iterating over a custom iterable

+ +

可以使用{{jsxref("Symbol.iterator")}} 方法去实现一个自定义迭代器。你必须确定自定义的迭代器方法返回一个迭代器对象,即它必须有一个next()

+ +
const myEmptyIterable = {
+    [Symbol.iterator]() {
+        return [] // [] is iterable, but it is not an iterator -- it has no next method.
+    }
+}
+
+Array.from(myEmptyIterable);  // TypeError: myEmptyIterable is not iterable
+
+ +

+
+

下面是正确用法

+ +
const myEmptyIterable = {
+    [Symbol.iterator]() {
+        return [][Symbol.iterator]()
+    }
+}
+
+Array.from(myEmptyIterable);  // []
+
+ +

参阅

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/json_bad_parse/index.html b/files/zh-cn/web/javascript/reference/errors/json_bad_parse/index.html new file mode 100644 index 0000000000..cac9176d80 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/json_bad_parse/index.html @@ -0,0 +1,111 @@ +--- +title: 'SyntaxError: JSON.parse: bad parsing' +slug: Web/JavaScript/Reference/Errors/JSON_bad_parse +tags: + - Errors + - JSON + - JavaScript + - SyntaxError + - 方法 +translation_of: Web/JavaScript/Reference/Errors/JSON_bad_parse +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
SyntaxError: JSON.parse: unterminated string literal
+SyntaxError: JSON.parse: bad control character in string literal
+SyntaxError: JSON.parse: bad character in string literal
+SyntaxError: JSON.parse: bad Unicode escape
+SyntaxError: JSON.parse: bad escape character
+SyntaxError: JSON.parse: unterminated string
+SyntaxError: JSON.parse: no number after minus sign
+SyntaxError: JSON.parse: unexpected non-digit
+SyntaxError: JSON.parse: missing digits after decimal point
+SyntaxError: JSON.parse: unterminated fractional number
+SyntaxError: JSON.parse: missing digits after exponent indicator
+SyntaxError: JSON.parse: missing digits after exponent sign
+SyntaxError: JSON.parse: exponent part is missing a number
+SyntaxError: JSON.parse: unexpected end of data
+SyntaxError: JSON.parse: unexpected keyword
+SyntaxError: JSON.parse: unexpected character
+SyntaxError: JSON.parse: end of data while reading object contents
+SyntaxError: JSON.parse: expected property name or '}'
+SyntaxError: JSON.parse: end of data when ',' or ']' was expected
+SyntaxError: JSON.parse: expected ',' or ']' after array element
+SyntaxError: JSON.parse: end of data when property name was expected
+SyntaxError: JSON.parse: expected double-quoted property name
+SyntaxError: JSON.parse: end of data after property name when ':' was expected
+SyntaxError: JSON.parse: expected ':' after property name in object
+SyntaxError: JSON.parse: end of data after property value in object
+SyntaxError: JSON.parse: expected ',' or '}' after property value in object
+SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal
+SyntaxError: JSON.parse: property names must be double-quoted strings
+SyntaxError: JSON.parse: expected property name or '}'
+SyntaxError: JSON.parse: unexpected character
+SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

{{jsxref("JSON.parse()")}} 会把一个字符串解析成 JSON 对象。如果字符串书写正确,那么其将会被解析成一个有效的 JSON,但是这个字符串被检测出错误语法的时候将会抛出错误。

+ +

示例

+ +

JSON.parse() 不允许在末尾添加多余的逗号

+ +

下面两行代码都会抛出错误:

+ +
JSON.parse('[1, 2, 3, 4, ]');
+JSON.parse('{"foo" : 1, }');
+// SyntaxError JSON.parse: unexpected character
+// at line 1 column 14 of the JSON data
+
+ +

省略末尾多余的逗号解析 JSON 就是正确:

+ +
JSON.parse('[1, 2, 3, 4 ]');
+JSON.parse('{"foo" : 1 }');
+ +

JSON 的属性名必须使用双引号

+ +

属性名上不能使用单引号,例如: 'foo'。

+ +
JSON.parse("{'foo' : 1 }");
+// SyntaxError: JSON.parse: expected property name or '}'
+// at line 1 column 2 of the JSON data
+ +

取而代之,写成 "foo":

+ +
JSON.parse('{"foo" : 1 }');
+ +

前导 0 和小数点

+ +

数字不能用 0 开头,比如01,并且你的小数点后面必须跟着至少一个数字。

+ +
JSON.parse('{"foo" : 01 }');
+// SyntaxError: JSON.parse: expected ',' or '}' after property value
+// in object at line 1 column 2 of the JSON data
+
+JSON.parse('{"foo" : 1. }');
+// SyntaxError: JSON.parse: unterminated fractional number
+// at line 1 column 2 of the JSON data
+
+ +

正确的写法应该是只写一个1,不书写前面的0。在小数点的后面至少要跟上一个数字:

+ +
JSON.parse('{"foo" : 1 }');
+JSON.parse('{"foo" : 1.0 }');
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/malformed_formal_parameter/index.html b/files/zh-cn/web/javascript/reference/errors/malformed_formal_parameter/index.html new file mode 100644 index 0000000000..edbee71c60 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/malformed_formal_parameter/index.html @@ -0,0 +1,61 @@ +--- +title: 'SyntaxError: Malformed formal parameter' +slug: Web/JavaScript/Reference/Errors/Malformed_formal_parameter +tags: + - Errors + - JavaScript + - SyntaxError +translation_of: Web/JavaScript/Reference/Errors/Malformed_formal_parameter +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
SyntaxError: malformed formal parameter (Firefox)
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里错了?

+ +

在至少带有两个参数的 Function() 构造器中它的最后一个参数是创建的新函数的源代码。剩下的都是新函数的参数。

+ +

构造器的参数有些情况下是无效的。 也许是你不小心用了一个关键字 if 或 var 作为参数名称,或者在参数列表中有一些杂乱的标点符号。 或者也许你不小心传递了一个无效的值,比如数字或对象。

+ +

好吧,这解决了我的问题。但是为什么不开始就说明白呢?

+ +

诚然,错误信息中的措辞稍微有些奇怪。"Formal parameter" 是 "function argument" 的另一种优美的同义。 我们使用 “malformed”(即畸形)这个词,因为所有的Firefox工程师都是19世纪哥特式恐怖小说的巨星。

+ +

示例

+ +

无效的

+ +
var f = Function("x y", "return x + y;");
+// SyntaxError (missing a comma)
+
+var f = Function("x,", "return x;");
+// SyntaxError (extraneous comma)
+
+var f = Function(37, "alert('OK')");
+// SyntaxError (numbers can't be argument names)
+
+ +

有效的

+ +
var f = Function("x, y", "return x + y;");  // correctly punctuated
+
+var f = Function("x", "return x;");
+
+// if you can, avoid using Function - this is much faster
+var f = function (x) { return x; };
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/malformed_uri/index.html b/files/zh-cn/web/javascript/reference/errors/malformed_uri/index.html new file mode 100644 index 0000000000..40bb10ae1d --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/malformed_uri/index.html @@ -0,0 +1,65 @@ +--- +title: 'URIError: malformed URI sequence' +slug: Web/JavaScript/Reference/Errors/Malformed_URI +tags: + - JavaScript + - URLError + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Malformed_URI +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
URIError: malformed URI sequence (Firefox)
+URIError: URI malformed (Chrome)
+
+ +

错误类型

+ +

{{jsxref("URIError")}}

+ +

哪里出错了?

+ +

URI 编码和解码不成功。传递给 {{jsxref("decodeURI")}}、{{jsxref("encodeURI")}}、{{jsxref("encodeURIComponent")}} 或者 {{jsxref("decodeURIComponent")}} 这些函数的参数不合法,导致函数无法正确对其进行编解码。

+ +

示例

+ +

编码

+ +

编码操作会将每一个字符实例替换为一到四个相对应的 UTF-8 编码形式的转义序列。如果试图编码一个非高-低位完整的代理字符,将会抛出一个 {{jsxref("URIError")}} 错误,例如:

+ +
encodeURI('\uD800');
+// "URIError: malformed URI sequence"
+
+encodeURI('\uDFFF');
+// "URIError: malformed URI sequence"
+
+ +

高-低位完整的代理字符是没问题的,例如:

+ +
encodeURI('\uD800\uDFFF');
+// "%F0%90%8F%BF"
+ +

解码

+ +

解码操作则是将已经经过编码的 URL 片段中的每一个转义序列替换为相对应的字符。如果相应的字符不存在,就会抛出错误:

+ +
decodeURIComponent('%E0%A4%A');
+// "URIError: malformed URI sequence"
+
+ +

输入没问题的话,通常是下面这样:

+ +
decodeURIComponent('JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B');
+// "JavaScript_шеллы"
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/missing_bracket_after_list/index.html b/files/zh-cn/web/javascript/reference/errors/missing_bracket_after_list/index.html new file mode 100644 index 0000000000..d1da610184 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/missing_bracket_after_list/index.html @@ -0,0 +1,56 @@ +--- +title: 'SyntaxError: missing ] after element list' +slug: Web/JavaScript/Reference/Errors/Missing_bracket_after_list +tags: + - Errors + - JavaScript + - SyntaxError +translation_of: Web/JavaScript/Reference/Errors/Missing_bracket_after_list +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
SyntaxError: missing ] after element list
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}.

+ +

哪里出错了?

+ +

数组初始化在某处出现了语法错误。比如缺少了右中括号("]") 或一个逗号 (",")。

+ +

示例

+ +

不正确的数组初始化

+ +
var list = [1, 2,
+
+var instruments = [
+  "Ukulele",
+  "Guitar",
+  "Piano"
+};
+
+var data = [{foo: "bar"} {bar: "foo"}];
+
+ +

正确的是:

+ +
var list = [1, 2];
+
+var instruments = [
+ "Ukulele",
+ "Guitar",
+ "Piano"
+];
+
+var data = [{foo: "bar"}, {bar: "foo"}];
+ +

相关

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/missing_colon_after_property_id/index.html b/files/zh-cn/web/javascript/reference/errors/missing_colon_after_property_id/index.html new file mode 100644 index 0000000000..7cfdf7e318 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/missing_colon_after_property_id/index.html @@ -0,0 +1,76 @@ +--- +title: 'SyntaxError: missing : after property id' +slug: Web/JavaScript/Reference/Errors/Missing_colon_after_property_id +tags: + - JavaScript + - 语法错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Missing_colon_after_property_id +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
SyntaxError: missing : after property id
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

当使用对象初始化语法创建对象的时候,需要使用半角冒号 (:) 将属性键与属性值隔开。

+ +
var obj = { propertyKey: 'value' };
+
+ +

示例

+ +

冒号与等号

+ +

下面的代码会运行失败,原因是对象初始化语法中不允许使用等号来代替冒号。

+ +
var obj = { propertyKey = 'value' };
+// SyntaxError: missing : after property id
+
+ +

修复方法就是使用冒号,或者是在对象创建之后使用方括号语法来为其设定新的属性。

+ +
var obj = { propertyKey: 'value' };
+
+// or alternatively
+
+var obj = { };
+obj['propertyKey'] = 'value';
+
+ +

空属性

+ +

不能像下面这样创建空属性:

+ +
var obj = { propertyKey; };
+// SyntaxError: missing : after property id
+
+ +

假如你需要创建一个无值属性,那么需要将它的值设置为 {{jsxref("null")}} 。

+ +
var obj = { propertyKey: null };
+ +

计算得来的属性

+ +

如果需要使用表达式来创建属性键,那么需要使用方括号。否则属性名称不会进行计算:

+ +
var obj = { 'b'+'ar': 'foo' };
+// SyntaxError: missing : after property id
+
+ +

把计算表达式放置到方括号([])中:

+ +
var obj = { ['b'+'ar']: 'foo' };
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/missing_curly_after_function_body/index.html b/files/zh-cn/web/javascript/reference/errors/missing_curly_after_function_body/index.html new file mode 100644 index 0000000000..36761114d1 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/missing_curly_after_function_body/index.html @@ -0,0 +1,66 @@ +--- +title: 'SyntaxError: missing } after function body' +slug: Web/JavaScript/Reference/Errors/Missing_curly_after_function_body +tags: + - JavaScript + - 语法错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Missing_curly_after_function_body +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
SyntaxError: missing } after function body
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

在创建函数的时候出现了语法错误。检查一下闭合花括号以及括号的顺序是否正确。将代码进行缩进或者美化可以让你更容易找到问题之所在。

+ +

示例

+ +

遗漏的闭合花括号

+ +

通常是因为在函数声明中遗漏了花括号:

+ +
var charge = function() {
+  if (sunny) {
+    useSolarCells();
+  } else {
+    promptBikeRide();
+};
+
+ +

正确的应该是这样的:

+ +
var charge = function() {
+  if (sunny) {
+    useSolarCells();
+  } else {
+    promptBikeRide();
+  }
+};
+ +

当使用立即调用函数表达式({{Glossary("IIFE")}})、闭包或者其他使用了大量的花括号以及括号的结构体的时候,问题会更加隐蔽。

+ +
(function() { if (true) { return false; } );
+
+ +

通常将代码语句按照层级缩进以及对缩进进行复核会有助于错误的发现。

+ +
(function() {
+  if (true) {
+    return false;
+  }
+});
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/missing_curly_after_property_list/index.html b/files/zh-cn/web/javascript/reference/errors/missing_curly_after_property_list/index.html new file mode 100644 index 0000000000..4c6a06e4e0 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/missing_curly_after_property_list/index.html @@ -0,0 +1,51 @@ +--- +title: 'SyntaxError: missing } after property list' +slug: Web/JavaScript/Reference/Errors/Missing_curly_after_property_list +tags: + - Errors + - JavaScript + - SyntaxError +translation_of: Web/JavaScript/Reference/Errors/Missing_curly_after_property_list +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
SyntaxError: missing } after property list
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

对象初始化的时候语法出错了。可能是遗漏了一个大括号,也可能是遗漏了逗号。还要检查是否以正确的顺序关闭了大括号或括号。 缩进或格式化代码也许可以更好帮助你看清这些芜杂的。

+ +

示例

+ +

遗漏的逗号

+ +

很多情况下,对象初始值代码会中缺少逗号:

+ +
var obj = {
+  a: 1,
+  b: { myProp: 2 }
+  c: 3
+};
+
+ +

正确的是:

+ +
var obj = {
+  a: 1,
+  b: { myProp: 2 },
+  c: 3
+};
+
+ +

相关

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/missing_formal_parameter/index.html b/files/zh-cn/web/javascript/reference/errors/missing_formal_parameter/index.html new file mode 100644 index 0000000000..9d8a069258 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/missing_formal_parameter/index.html @@ -0,0 +1,80 @@ +--- +title: 'SyntaxError: missing formal parameter' +slug: Web/JavaScript/Reference/Errors/Missing_formal_parameter +tags: + - JavaScript + - 类型错误 + - 错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Missing_formal_parameter +--- +
{{jsSidebar("Errors")}}
+ +

信息提示

+ +
SyntaxError: missing formal parameter (Firefox)
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

“形式参数” 是 “函数参数”一种更好的说法。函数声明缺少合法的参数定义。在函数声明中,参数定义必须为标记符({{Glossary("Identifier", "identifiers")}}), 而不是任何类似于数字、字符串或者对象的值。函数声明和函数调用是两个不同的步骤。函数声明中的参数需要使用标记符,而仅仅在函数被呼叫(调用)的时候才可以传入其所需要的值。

+ +

在 {{glossary("JavaScript")}} 中,标记符只能由字母、数字、"$" 以及 "_" 构成,并且不能以数字开头。标记符与字符串的区别在于字符串是数据,而标记符属于代码的一部分。

+ +

示例

+ +

在构造一个函数的时候,函数参数必须为标记符。下面列举的函数声明都是无效的,因为它们在参数部分使用的是数值:

+ +
function square(3) {
+  return number * number;
+};
+// SyntaxError: missing formal parameter
+
+function greet("Howdy") {
+  return greeting;
+};
+// SyntaxError: missing formal parameter
+
+function log({ obj: "value"}) {
+  console.log(arg)
+};
+// SyntaxError: missing formal parameter
+
+ +

需要在函数声明中使用标记符:

+ +
function square(number) {
+  return number * number;
+};
+
+function greet(greeting) {
+  return greeting;
+};
+
+function log(arg) {
+  console.log(arg)
+};
+ +

之后可以传入你想要传入的实际参数调用函数:

+ +
square(2); // 4
+
+greet("Howdy"); // "Howdy"
+
+log({obj: "value"}); // Object { obj: "value" }
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/missing_initializer_in_const/index.html b/files/zh-cn/web/javascript/reference/errors/missing_initializer_in_const/index.html new file mode 100644 index 0000000000..f87d78f746 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/missing_initializer_in_const/index.html @@ -0,0 +1,57 @@ +--- +title: 'SyntaxError: missing = in const declaration' +slug: Web/JavaScript/Reference/Errors/Missing_initializer_in_const +tags: + - JavaScript + - 语法错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Missing_initializer_in_const +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
SyntaxError: missing = in const declaration (Firefox)
+SyntaxError: Missing initializer in const declaration (Chrome)
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

常量指的是在程序正常运行过程中不能被修改的值。它的值不能通过二次赋值来改变,同时也不能被再次声明。在 JavaScript 中,常量在声明时使用  const 关键字来修饰。常量需要初始化器;也就是说,必须在声明的同时为其赋值(鉴于常量值指定之后不能再进行修改,这样做是容易理解的)。

+ +

示例

+ +

初始值缺失

+ +

不同于 var 或 let 关键字,必须在常量声明中为其赋值。下面的例子中会报错:

+ +
const COLUMNS;
+// SyntaxError: missing = in const declaration
+ +

错误修正

+ +

修正这个问题的方法有很多种。仔细检查对于问题中的常量,你想要达到什么目标。

+ +

添加常量值

+ +

在声明语句中为其赋值:

+ +
const COLUMNS = 80;
+ +

const, let 还是 var?

+ +

如果你并不想声明一个常量值,那么就不要使用 const 关键字。或许你想要的是使用  let 来声明一个块状作用域变量或者是用 var 声明一个全局变量。这两者都不需要设置初始值。

+ +
let columns;
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/missing_name_after_dot_operator/index.html b/files/zh-cn/web/javascript/reference/errors/missing_name_after_dot_operator/index.html new file mode 100644 index 0000000000..634008c21b --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/missing_name_after_dot_operator/index.html @@ -0,0 +1,67 @@ +--- +title: 'SyntaxError: missing name after . operator' +slug: Web/JavaScript/Reference/Errors/Missing_name_after_dot_operator +tags: + - JavaScript + - 语法错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Missing_name_after_dot_operator +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
SyntaxError: missing name after . operator
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

点操作符 (.) 用于属性访问。你需要指定要访问的属性名称。对于属性名称是运算表达式的属性访问,需要将属性访问的方式从点操作符转换为方括号操作符。这样你就可以在其中进行表达式运算了。或许你想要进行字符串拼接操作?那么请使用加号操作符(+)。请参考下面的示例。

+ +

示例

+ +

属性访问

+ +

在 JavaScript 中,属性访问器或者使用点操作符 (.),或者使用方括号操作符 ([]),但是二者不能同时使用。方括号操作符允许属性名称为运算表达式的属性访问。

+ +
var obj = { foo: { bar: "baz", bar2: "baz2" } };
+var i = 2;
+
+obj.[foo].[bar]
+// SyntaxError: missing name after . operator
+
+obj.foo."bar"+i;
+// SyntaxError: missing name after . operator
+
+ +

为了进行代码修复,你需要向下面这样来访问对象:

+ +
obj.foo.bar; // "baz"
+// or alternatively
+obj["foo"]["bar"]; // "baz"
+
+// computed properties require square brackets
+obj.foo["bar" + i]; // "baz2"
+
+ +

属性访问与字符串拼接

+ +

如果你是中其他编程语言(如 {{Glossary("PHP")}})转到 JavaScript 的,很容易将点操作符 (.) 与连接操作符 (+) 混用:

+ +
console.log("Hello" . "world");
+
+// SyntaxError: missing name after . operator
+ +

相反要使用加号来进行字符串拼接:

+ +
console.log("Hello" + "World");
+ +

相关页面

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html b/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html new file mode 100644 index 0000000000..5d3dfe8809 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html @@ -0,0 +1,42 @@ +--- +title: 'SyntaxError: missing ) after argument list' +slug: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list +tags: + - JavaScript + - 语法错误 + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list +--- +
{{jsSidebar("Errors")}}
+ +

消息

+ +
语法错误: 参数列表后面缺少 )
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}.

+ +

什么地方出错了?

+ +

有一个函数在调用时出现错误。这可能是一个错误,丢失运算符或者转义字符等。

+ +

示例

+ +

因为没有使用 ”+“ 操作符来连接字符串,JavaScript 认为 log 函数的参数的值只是 “PI: ”,在这种情况下,它应该用一个右括号作为结束。

+ +
console.log("PI: " Math.PI);
+// SyntaxError: missing ) after argument list
+
+ +

你可以正确的调用 log 函数通过加上 ”+“ 操作符。

+ +
console.log("PI: " + Math.PI);
+// "PI: 3.141592653589793"
+ +

相关页面

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_condition/index.html b/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_condition/index.html new file mode 100644 index 0000000000..e2db63da04 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_condition/index.html @@ -0,0 +1,69 @@ +--- +title: 'SyntaxError: missing ) after condition' +slug: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_condition +tags: + - JavaScript + - 语法错误 + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_condition +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
SyntaxError: missing ) after condition
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

这个错误与 if 条件语句是如何写的有关。在任何编程语言中,代码都需要做出一些判断,然后根据不同的判断结果来执行不同的操作。if 语句会在其指定的判断条件为真的时候执行。在 JavaScript 中,条件表达式必须出现在 if 关键字后面的一对括号中,像下面这样:

+ +
if (condition) {
+  // do something if the condition is true
+}
+ +

示例

+ +

下面这种情况的出现可能只是出于大意,需要仔细检查代码中的括号。

+ +
if (3 > Math.PI {
+  console.log("wait what?");
+}
+
+// SyntaxError: missing ) after condition
+
+ +

修复代码的方法就是添加闭合条件表达式的右括号。

+ +
if (3 > Math.PI) {
+  console.log("wait what?");
+}
+ +

如果你是从其他语言转到 JavaScript 的,那么很容易在 JavaScript 中使用与之含义不同或者没有任何意义的关键字。

+ +
if (done is true) {
+ console.log("we are done!");
+}
+
+// SyntaxError: missing ) after condition
+
+ +

相反你需要使用正确的比较操作符, 如下:

+ +
if (done === true) {
+ console.log("we are done!");
+}
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/zh-cn/web/javascript/reference/errors/missing_semicolon_before_statement/index.html new file mode 100644 index 0000000000..e3e6a98c88 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/missing_semicolon_before_statement/index.html @@ -0,0 +1,81 @@ +--- +title: 'SyntaxError: missing ; before statement' +slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
SyntaxError: Expected ';' (Edge)
+ +
 SyntaxError: missing ; before statement (Firefox)
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}.

+ +

哪里出错了?

+ +

某个地方丢失了一个(;)。 JavaScript 语句必须以分号结束。 有一些是由 自动分号插入(ASI) 的使用所影响到的, 但在这种情况下,你需要提供一个分号,以便于JavaScript可以将源代码解析正确。然而,通常情况下,这个错误只是另一个错误一个导致的,如不正确转义字符串,使用var的错误。你也可能有太多的括号的地方。当出现此错误时,仔细检查语法。

+ +

例子

+ +

 

+ +

转义字符串

+ +

这个错误可能发生不正确时容易转义字符串JavaScript引擎是希望你的字符串的末尾已经。例如:

+ +
var foo = 'Tom's bar';
+// SyntaxError: missing ; before statement
+ +

你可以用双引号,或者用\转义:

+ +
var foo = "Tom's bar";
+var foo = 'Tom\'s bar';
+
+ +

用var声明属性

+ +

你不能将带有变量声明的对象或数组的属性用var来声明。

+ +
var obj = {};
+var obj.foo = "hi"; // SyntaxError missing ; before statement
+
+var array = [];
+var array[0] = "there"; // SyntaxError missing ; before statement
+
+ +

而是省略掉var关键词:

+ +
var obj = {};
+obj.foo = "hi";
+
+var array = [];
+array[0] = "there";
+
+ +

不推荐使用的关键字

+ +

如果你用的是另一种编程语言,那么在javaScript中使用不具有相同或完全没有意义的关键字也是很常见的:

+ +
def print(info){
+  console.log(info);
+}; // SyntaxError missing ; before statement
+ +

因此,建议使用function而不是def

+ +
function print(info){
+  console.log(info);
+};
+ +

 

+ +

参考

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/more_arguments_needed/index.html b/files/zh-cn/web/javascript/reference/errors/more_arguments_needed/index.html new file mode 100644 index 0000000000..b042af14bb --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/more_arguments_needed/index.html @@ -0,0 +1,48 @@ +--- +title: 'TypeError: More arguments needed' +slug: Web/JavaScript/Reference/Errors/More_arguments_needed +tags: + - Errors + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/More_arguments_needed +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
TypeError: Object.create requires more than 0 arguments
+TypeError: Object.setPrototypeOf requires more than 1 argument
+TypeError: Object.defineProperties requires more than 0 arguments
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}.

+ +

哪里出错了?

+ +

调用函数的时候出现了错误。需要提供更多的参数。

+ +

示例

+ +

{{jsxref("Object.create()")}} 方法要求至少有一个参数,而 {{jsxref("Object.setPrototypeOf()")}} 方法要求至少有两个参数:

+ +
var obj = Object.create();
+// TypeError: Object.create requires more than 0 arguments
+
+var obj = Object.setPrototypeOf({});
+// TypeError: Object.setPrototypeOf requires more than 1 argument
+
+ +

你可以将 {{jsxref("null")}} 设置为原型:

+ +
var obj = Object.create(null);
+
+var obj = Object.setPrototypeOf({}, null);
+ +

相关

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/negative_repetition_count/index.html b/files/zh-cn/web/javascript/reference/errors/negative_repetition_count/index.html new file mode 100644 index 0000000000..780bdabcf4 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/negative_repetition_count/index.html @@ -0,0 +1,45 @@ +--- +title: 'RangeError: repeat count must be non-negative' +slug: Web/JavaScript/Reference/Errors/Negative_repetition_count +tags: + - Errors + - JavaScript + - RangeError + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Negative_repetition_count +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
RangeError: repeat count must be non-negative (Firefox)
+RangeError: Invalid count value (Chrome)
+
+ +

错误类型

+ +

{{jsxref("RangeError")}}

+ +

发生了什么?

+ +

代码中使用了 {{jsxref("String.prototype.repeat()")}}方法。它有一个计数参数,表示重复该字符串的次数。该参数必须在 0 及正 {{jsxref("Infinity")}} 之间,且不能为负数。该值的合法范围可以这样表示: [0, +∞)。

+ +

示例

+ +

无效的

+ +
'abc'.repeat(-1); // RangeError 
+ +

有效的

+ +
'abc'.repeat(0);    // ''
+'abc'.repeat(1);    // 'abc'
+'abc'.repeat(2);    // 'abcabc'
+'abc'.repeat(3.5);  // 'abcabcabc' (count will be converted to integer)
+
+ +

See also

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/no_non-null_object/index.html b/files/zh-cn/web/javascript/reference/errors/no_non-null_object/index.html new file mode 100644 index 0000000000..6369e8eaf1 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/no_non-null_object/index.html @@ -0,0 +1,65 @@ +--- +title: 'TypeError: "x" is not a non-null object' +slug: Web/JavaScript/Reference/Errors/No_non-null_object +tags: + - JavaScript + - 类型错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/No_non-null_object +--- +
{{JSSidebar("Errors")}}
+ +

提示信息

+ +
TypeError: "x" is not a non-null object (Firefox)
+TypeError: Property description must be an object: "x" (Chrome)
+TypeError: Invalid value used in weak set (Chrome)
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

在期待出现对象类型的值的地方而没有提供。{{jsxref("null")}} 不是对象类型,因此不起作用。必须在给定的场景下提供一个合适的对象。

+ +

示例

+ +

期望的属性描述器

+ +

当使用诸如 {{jsxref("Object.create()")}} 或 {{jsxref("Object.defineProperty()")}} 及{jsxref("Object.defineProperties()")}} 方法时,可选的属性描述器参数需要提供一个描述器对象。提供非对象类型的值(例如数字)将会报错:

+ +
Object.defineProperty({}, 'key', 1);
+// TypeError: 1 is not a non-null object
+
+Object.defineProperty({}, 'key', null);
+// TypeError: null is not a non-null object
+
+ +

一个合法的描述器对象类似于下面这样:

+ +
Object.defineProperty({}, 'key', { value: 'foo', writable: false });
+
+ +

WeakMap 和 WeakSet 对象需要对象类型的键

+ +

{{jsxref("WeakMap")}} 和 {{jsxref("WeakSet")}} 对象只能存储对象类型的键,而不能使用其他类型的。

+ +
var ws = new WeakSet();
+ws.add('foo');
+// TypeError: "foo" is not a non-null object
+ +

用对象类型的值来替换:

+ +
ws.add({foo: 'bar'});
+ws.add(window);
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/no_properties/index.html b/files/zh-cn/web/javascript/reference/errors/no_properties/index.html new file mode 100644 index 0000000000..5e904dd8ab --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/no_properties/index.html @@ -0,0 +1,36 @@ +--- +title: 'TypeError: "x" has no properties' +slug: Web/JavaScript/Reference/Errors/No_properties +translation_of: Web/JavaScript/Reference/Errors/No_properties +--- +
{{jsSidebar("Errors")}}
+ +

错误信息

+ +
TypeError: null has no properties
+TypeError: undefined has no properties
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}.

+ +

哪里出错了?

+ +

 {{jsxref("null")}} 和 {{jsxref("undefined")}}中,没有你需要的属性。

+ +

例子

+ +
null.foo;
+// 错误类型: null没有这个属性
+
+undefined.bar;
+// 错误类型: undefined没有这个属性
+
+ +

参考

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/no_variable_name/index.html b/files/zh-cn/web/javascript/reference/errors/no_variable_name/index.html new file mode 100644 index 0000000000..4b69a5cec1 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/no_variable_name/index.html @@ -0,0 +1,83 @@ +--- +title: 'SyntaxError: missing variable name' +slug: Web/JavaScript/Reference/Errors/No_variable_name +tags: + - JavaScript + - 语法错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/No_variable_name +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
SyntaxError: missing variable name (Firefox)
+SyntaxError: Unexpected token = (Chrome)
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

缺失变量名。这有很大的可能性是由你的代码中的语法错误造成的。也许是什么地方的逗号出了问题,或者是你正在绞尽脑汁想一个合适的名字。完全可以理解!为变量起名确实让人头疼。

+ +

示例

+ +

变量名缺失

+ +
var = "foo";
+
+ +

为变量起一个合适的明确确实不是一件容易的事情。这种经历每个人都遇到过。

+ +
var ohGodWhy = "foo";
+ +

保留字不能作为变量名

+ +

有一些名称是作为保留字而存在的。不好意思,你不能使用!:(

+ +
var debugger = "whoop";
+// SyntaxError: missing variable name
+
+ +

一次性声明多个变量

+ +

在一次性声明多个变量的时候要特别留意逗号。看看是否有多余的逗号?以及是否不小心把逗号用作了分号?

+ +
var x, y = "foo",
+var x, = "foo"
+
+var first = document.getElementById('one'),
+var second = document.getElementById('two'),
+
+// SyntaxError: missing variable name
+
+ +

修复后的代码:

+ +
var x, y = "foo";
+var x = "foo";
+
+var first = document.getElementById('one');
+var second = document.getElementById('two');
+ +

数组

+ +

在 JavaScript 中 {{jsxref("Array")}} 字面量需要使用方括号将值包裹起来。下面这样是不对的:

+ +
var arr = 1,2,3,4,5;
+// SyntaxError: missing variable name
+
+ +

这样写才是正确的:

+ +
var arr = [1,2,3,4,5];
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/non_configurable_array_element/index.html b/files/zh-cn/web/javascript/reference/errors/non_configurable_array_element/index.html new file mode 100644 index 0000000000..d38da28248 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/non_configurable_array_element/index.html @@ -0,0 +1,81 @@ +--- +title: 'TypeError: can''t delete non-configurable array element' +slug: Web/JavaScript/Reference/Errors/Non_configurable_array_element +tags: + - JavaScript + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Non_configurable_array_element +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
TypeError: can't delete non-configurable array element (Firefox)
+TypeError: Cannot delete property '2' of [object Array] (Chrome)
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

这个错误提示发生于当试图缩短一个数组的长度的时候,其中有元素是不可配置的(non-configurable)。正常情况下,缩短数组的长度,则超出限度的元素会被删除,而这里指的是这种操作失效的情况。

+ +

 configurable  特性控制着属性是否可以从对象中删除,以及它的特性(除了 writable 之外)是否可以发生改变。

+ +

通常,使用数组初始化语句创建的对象是可配置的,而通过 {{jsxref("Object.defineProperty()")}} 创建的属性,默认则是不可配置的。

+ +

示例

+ +

通过 Object.defineProperty 创建的不可配置属性

+ +

使用 {{jsxref("Object.defineProperty()")}} 且在没有明确将属性设定为可配置的情况下,默认可以创建不可配置属性。

+ +
var arr = [];
+Object.defineProperty(arr, 0, {value: 0});
+Object.defineProperty(arr, 1, {value: "1"});
+
+arr.length = 1;
+// TypeError: can't delete non-configurable array element
+
+ +

如果想要缩短数组长度的话,需要将其中的元素设置为可配置的。

+ +
var arr = [];
+Object.defineProperty(arr, 0, {value: 0, configurable: true});
+Object.defineProperty(arr, 1, {value: "1", configurable: true});
+
+arr.length = 1;
+
+ +

密封的数组

+ +

 {{jsxref("Object.seal()")}} 函数会将数组中现存的所有元素标记为不可配置。

+ +
var arr = [1,2,3];
+Object.seal(arr);
+
+arr.length = 1;
+// TypeError: can't delete non-configurable array element
+
+ +

(为了解决上述问题,)或者是移除 {{jsxref("Object.seal()")}} 调用,或者将数组拷贝一份。在拷贝数组的情况下,缩短备份数组的长度并不会修改原始数组的长度。

+ +
var arr = [1,2,3];
+Object.seal(arr);
+
+// Copy the initial array to shorten the copy
+var copy = Array.from(arr);
+copy.length = 1;
+// arr.length == 3
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/not_a_codepoint/index.html b/files/zh-cn/web/javascript/reference/errors/not_a_codepoint/index.html new file mode 100644 index 0000000000..769e6daa0c --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/not_a_codepoint/index.html @@ -0,0 +1,51 @@ +--- +title: 'RangeError: argument is not a valid code point' +slug: Web/JavaScript/Reference/Errors/Not_a_codepoint +translation_of: Web/JavaScript/Reference/Errors/Not_a_codepoint +--- +
{{jsSidebar("Errors")}}
+ +

错误信息

+ +
RangeError: {0} is not a valid code point (Firefox)
+RangeError: Invalid code point {0} (Chrome)
+
+ +

错误类型

+ +

{{jsxref("RangeError")}}

+ +

什么地方出错了?

+ +

 {{jsxref("String.fromCodePoint()")}} 这个方法只能接受有效的码位(code point) 。

+ +

码位( code point)是组成码空间(或代码页)的数值,范围是 0 到 0x10FFFF。

+ +

 {{jsxref("NaN")}},负整数(-1),非整数(3.14),或编号大于0x10FFFF (1114111) 的字符,无法使用该方法。

+ +

范例

+ +

无效的例子

+ +
String.fromCodePoint('_');      // RangeError
+String.fromCodePoint(Infinity); // RangeError
+String.fromCodePoint(-1);       // RangeError
+String.fromCodePoint(3.14);     // RangeError
+String.fromCodePoint(3e-2);     // RangeError
+String.fromCodePoint(NaN);      // RangeError
+ +

有效的例子

+ +
String.fromCodePoint(42);       // "*"
+String.fromCodePoint(65, 90);   // "AZ"
+String.fromCodePoint(0x404);    // "\u0404"
+String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
+String.fromCodePoint(194564);   // "\uD87E\uDC04"
+String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/not_a_constructor/index.html b/files/zh-cn/web/javascript/reference/errors/not_a_constructor/index.html new file mode 100644 index 0000000000..60279ed3c8 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/not_a_constructor/index.html @@ -0,0 +1,95 @@ +--- +title: 'TypeError: "x" is not a constructor' +slug: Web/JavaScript/Reference/Errors/Not_a_constructor +tags: + - Errors + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Not_a_constructor +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
TypeError: "x" is not a constructor
+
+TypeError: Math is not a constructor
+TypeError: JSON is not a constructor
+TypeError: Symbol is not a constructor
+TypeError: Reflect is not a constructor
+TypeError: Intl is not a constructor
+TypeError: SIMD is not a constructor
+TypeError: Atomics is not a constructor
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

是因为尝试将不是构造器的对象或者变量来作为构造器使用。参考 {{Glossary("constructor")}} 或者 new operator 来了解什么是构造器。

+ +

有很多的全局对象比如 {{jsxref("String")}}、{{jsxref("Array")}} 等等都是可以使用 new 操作符的构造器。但是有一些全局对象并不是,且其属性和方法都是静态的。下面的 JavaScript 标准内置对象都不是构造器:{{jsxref("Math")}},{{jsxref("JSON")}},{{jsxref("Symbol")}},{{jsxref("Reflect")}},{{jsxref("Intl")}},{{jsxref("SIMD")}},{{jsxref("Atomics")}}。

+ +

Generator functions 也不能作为构造器来使用。

+ +

示例

+ +

无效的

+ +
var Car = 1;
+new Car();
+// TypeError: Car is not a constructor
+
+new Math();
+// TypeError: Math is not a constructor
+
+new Symbol();
+// TypeError: Symbol is not a constructor
+
+function* f() {};
+var obj = new f;
+// TypeError: f is not a constructor
+
+ +

一个构造器

+ +

假设你想为汽车创建一个对象类型。 你希望此类型的对象被称为 car,并且您希望它具有make,model 和 year 属性。 为此,你编写以下函数:

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+
+ +

现在你可以创建一个名为 mycar 的对象,如下所示:

+ +
var mycar = new Car("Eagle", "Talon TSi", 1993);
+ +

关于 Promises 

+ +

当返回了一个 immediately-resolved 或者 immediately-rejected Promise 的时候,你根本不需要去创建、操作一个新的 Promise 对象。

+ +

这是不合法的(Promise constructor 被错误的调用了)且会抛出一个 错误 TypeError: this is not a constructor exception:

+ +
return new Promise.resolve(true);
+
+ +

使用 Promise.resolve() 或者 Promise.reject() 静态方法来代替:

+ +
// 这是合法的,但是没必要这么长:
+return new Promise((resolve, reject) => { resolve(true); })
+
+// 用静态方法来代替:
+return Promise.resolve(true);
+return Promise.reject(false);
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/not_a_function/index.html b/files/zh-cn/web/javascript/reference/errors/not_a_function/index.html new file mode 100644 index 0000000000..fc4f664e1d --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/not_a_function/index.html @@ -0,0 +1,167 @@ +--- +title: 'TypeError: "x" is not a function' +slug: Web/JavaScript/Reference/Errors/Not_a_function +tags: + - Errors + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Not_a_function +--- +
{{jsSidebar("Errors")}}
+ +
JavaScript异常"is not a function"会在试图去调用一个像函数一样的值,但是该值实际上不是函数时被抛出.
+ +

信息

+ +
TypeError: Object doesn't support property or method {x} (Edge)
+TypeError: "x" is not a function
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

问题出在你试图去调用一个像函数一样的值,但是该值实际上不是函数,有时候你的代码需要调用一些函数,但是那种值并不能当作函数来被调用。

+ +

也许函数名称上有错别字? 也许你正在调用Object对象没有这个方法? 例如,在JavaScript中单纯的对象(Object)没有map函数,但是JavaScript数组(Array)对象却有这个函数。

+ +

再比如,在JavaScript中很多原生对象的内置方法需要你提供一个(回调)函数。 所以你必须提供一个函数,以使这些方法正常工作:

+ + + +

例子

+ +

函数的名称错误

+ +

函数的名称拼写错误,这种情况是经常发生的:

+ +
var x = document.getElementByID("foo");
+// TypeError: document.getElementByID is not a function
+
+ +

正确的方法名应该是 getElementById:

+ +
var x = document.getElementById("foo");
+
+ +

调用Object类型中不存在的方法

+ +

对于某些特殊的方法,它只属于某些特定的原生对象中,你必须提供一个回调函数才能正常运行。例如:这里调用了一个 {{jsxref("Array.prototype.map()")}} 方法,但是这方法只能被 {{jsxref("Array")}} 对象所调用。 

+ +
var obj = { a: 13, b: 37, c: 42 };
+
+obj.map(function(num) {
+  return num * 2;
+});
+
+// TypeError: obj.map is not a function
+ +

正确的做法,使用一个数组来代替:

+ +
var numbers = [1, 4, 9];
+
+numbers.map(function(num) {
+  return num * 2;
+});
+
+// Array [ 2, 8, 18 ]
+
+ +

函数与已有属性重名

+ +

当您在创建类时,可能会存在某个属性和某个方法的名称相同,当您在调用该函数时,编译器会认为该函数不存在.

+ +
var Dog = function () {
+ this.age = 11;
+ this.color = "black";
+ this.name = "Ralph";
+ return this;
+}
+
+Dog.prototype.name = function(name) {
+ this.name = name;
+ return this;
+}
+
+
+var myNewDog = new Dog();
+myNewDog.name("Cassidy"); //Uncaught TypeError: myNewDog.name is not a function
+
+ +

正确的做法是使用不同的变量名.

+ +
var Dog = function () {
+ this.age = 11;
+ this.color = "black";
+ this.dogName = "Ralph"; //Using this.dogName instead of .name
+ return this;
+}
+
+Dog.prototype.name = function(name) {
+ this.dogName = name;
+ return this;
+}
+
+
+var myNewDog = new Dog();
+myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' }
+ +

使用括号进行乘法运算

+ +

在数学中,您可以将 2 × (3 + 5) 写为 2*(3 + 5) 或者省略为 2(3 + 5).

+ +

使用后者时将会抛出错误:

+ +
const sixteen = 2(3 + 5);
+alert('2 x (3 + 5) is ' + String(sixteen));
+//Uncaught TypeError: 2 is not a function
+ +

您可以添加乘法运算符 * 来改正代码:

+ +
const sixteen = 2 * (3 + 5);
+alert('2 x (3 + 5) is ' + String(sixteen));
+//2 x (3 + 5) is 16
+ +

正确地导入和导出模块

+ +

确保正确导入模块.

+ +

以下为一个示例模块 (helpers.js)

+ +
let helpers = function () { };
+
+helpers.groupBy = function (objectArray, property) {
+  return objectArray.reduce(function (acc, obj) {
+    var key = obj[property];
+    if (!acc[key]) {
+      acc[key] = [];
+    }
+    acc[key].push(obj);
+    return acc;
+  },
+{});
+}
+
+export default helpers;
+ +

在 App.js中正确导入该模块:

+ +
import helpers from './helpers'
+ +

相关

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/not_defined/index.html b/files/zh-cn/web/javascript/reference/errors/not_defined/index.html new file mode 100644 index 0000000000..a092f394ec --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/not_defined/index.html @@ -0,0 +1,66 @@ +--- +title: 'ReferenceError: "x" is not defined' +slug: Web/JavaScript/Reference/Errors/Not_defined +translation_of: Web/JavaScript/Reference/Errors/Not_defined +--- +

{{jsSidebar("Errors")}}

+ +

错误信息

+ +
ReferenceError: "x" is not defined
+
+ +

错误类型

+ +

{{jsxref("ReferenceError")}}.

+ +

什么地方出错了?

+ +

在某些地方引用一个不存在的变量的时候。当你使用变量的时候,这个变量必须是已经被声明的,或者你可以确保它在你当前的脚本或作用域 ({{Glossary("scope")}}) 中可用。

+ +
+

注意: 当你加载一个库的时候(例如 jQuery),请确保你在这个库加载完毕后再使用这个库中的变量,如“$”。将你想加载的库的 {{HTMLElement("script")}} 标签放置在你的代码前面。

+
+ +

示例

+ +

变量没有被声明

+ +
foo.substring(1); // ReferenceError: foo is not defined
+
+ +

“foo” 变量没有在任何地方被声明。它需要是某种字符串,这样 {{jsxref("String.prototype.substring()")}} 方法才可以正常工作。

+ +
var foo = 'bar';
+foo.substring(1); // "ar"
+ +

错误的作用域

+ +

变量必须是在它当前的执行环境中可用的。在一个函数(function)中定义的变量不能从这个函数外部的任何地方访问,因为这个变量的作用域仅在这个函数的内部。

+ +
function numbers () {
+  var num1 = 2,
+      num2 = 3;
+  return num1 + num2;
+}
+
+console.log(num1); // ReferenceError num1 is not defined.
+ +

然而,一个函数可用使用在它所被定义的作用域中的所有变量。换句话说,当一个函数被定义在全局作用域的时候,它可以访问所有在全局作用域中定义的变量。

+ +
var num1 = 2,
+    num2 = 3;
+
+function numbers () {
+  return num1 + num2;
+}
+
+console.log(num1); // 2
+ +

相关页面

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/precision_range/index.html b/files/zh-cn/web/javascript/reference/errors/precision_range/index.html new file mode 100644 index 0000000000..42e2c703a9 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/precision_range/index.html @@ -0,0 +1,96 @@ +--- +title: 'RangeError: precision is out of range' +slug: Web/JavaScript/Reference/Errors/Precision_range +tags: + - JavaScript + - 范围错误 + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Precision_range +--- +
{{jsSidebar("Errors")}}
+ +

描述

+ +
RangeError: precision {0} out of range (Firefox)
+RangeError: toExponential() argument must be between 0 and 20 (Chrome)
+RangeError: toFixed() digits argument must be between 0 and 20 (Chrome)
+RangeError: toPrecision() argument must be between 1 and 21 (Chrome)
+
+ +

错误类型

+ +

{{jsxref("RangeError")}}

+ +

什么地方出错了?

+ +

以下的某个方法传入了一个超出精度范围的参数:

+ + + +

通常这些方法允许的参数范围介于0和20(或21)之间。需要注意的是,ECMAScript标准是允许扩展这个范围的。

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodFirefox (SpiderMonkey)Chrome, Opera (V8)
{{jsxref("Number.prototype.toExponential()")}}0 to 1000 to 20
{{jsxref("Number.prototype.toFixed()")}}-20 to 1000 to 20
{{jsxref("Number.prototype.toPrecision()")}}1 to 1001 to 21
+ +

示例

+ +

错误的示例

+ +
77.1234.toExponential(-1);  // RangeError
+77.1234.toExponential(101); // RangeError
+
+2.34.toFixed(-100);         // RangeError
+2.34.toFixed(1001);         // RangeError
+
+1234.5.toPrecision(-1);     // RangeError
+1234.5.toPrecision(101);    // RangeError
+
+ +

正确的示例

+ +
77.1234.toExponential(4); // 7.7123e+1
+77.1234.toExponential(2); // 7.71e+1
+
+2.34.toFixed(1); // 2.3
+2.35.toFixed(1); // 2.4 (note that it rounds up in this case)
+
+5.123456.toPrecision(5); // 5.1235
+5.123456.toPrecision(2); // 5.1
+5.123456.toPrecision(1); // 5
+
+ +

相关页面

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/property_access_denied/index.html b/files/zh-cn/web/javascript/reference/errors/property_access_denied/index.html new file mode 100644 index 0000000000..7b90b8be6f --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/property_access_denied/index.html @@ -0,0 +1,45 @@ +--- +title: 'Error: Permission denied to access property "x"' +slug: Web/JavaScript/Reference/Errors/Property_access_denied +tags: + - Error + - Permission denied + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Property_access_denied +--- +
{{jsSidebar("Errors")}}
+ +

消息

+ +
Error: Permission denied to access property "x"
+
+ +

错误类型

+ +

{{jsxref("Error","错误")}}.

+ +

什么地方出错了?

+ +

尝试访问无权访问的对象。这很可能出现在使用{{HTMLElement("iframe")}}元素时加载了一个不同域名下的页面,这在访问子页面时会违背同源策略

+ +

示例

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <iframe id="myframe" src="http://www1.w3c-test.org/common/blank.html"></iframe>
+    <script>
+      console.log(document.getElementById('myframe').contentWindow.document);
+      // Error: Permission denied to access property "document"
+    </script>
+  </head>
+  <body></body>
+</html>
+
+ +

可以参考

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/read-only/index.html b/files/zh-cn/web/javascript/reference/errors/read-only/index.html new file mode 100644 index 0000000000..ecdc225497 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/read-only/index.html @@ -0,0 +1,76 @@ +--- +title: 'TypeError: "x" is read-only' +slug: Web/JavaScript/Reference/Errors/Read-only +translation_of: Web/JavaScript/Reference/Errors/Read-only +--- +
{{jsSidebar("Errors")}}
+ +

报错消息

+ +
TypeError: "x" is read-only (Firefox) //格式错误:"x"只读。(x可以代表任意值)
+TypeError: 0 is read-only (Firefox)
+TypeError: Cannot assign to read only property 'x' of #<Object> (Chrome)
+//格式错误:对象的x属性是只读的不能设置 (chrome)
+TypeError: Cannot assign to read only property '0' of [object Array] (Chrome)
+
+ +

错误格式

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

全局变量或对象属性被设置为只读 (专业点讲,就是这条数据属性禁止写入.)

+ +

这条错误值发生在strict mode code(俗称严格模式). 正常情况下,是没有报错的。

+ +

例如

+ +

无效例子(也就是下面这么做会导致报这种错)

+ +

只读属性不能直接创建, 但我们可以通过{{jsxref("Object.defineProperty()")}} 或 {{jsxref("Object.freeze()")}}设置.

+ +
"use strict";
+var obj = Object.freeze({name: "Elsa", score: 157});
+obj.score = 0;  // TypeError
+
+"use strict";
+Object.defineProperty(this, "LUNG_COUNT", {value: 2, writable: false});
+LUNG_COUNT = 3;  // TypeError
+
+"use strict";
+var frozenArray = Object.freeze([0, 1, 2]);
+frozenArray[0]++;  // TypeError
+
+还有几个JavaScript内置属性. 如果你尝试修改一个常量.
+
+"use strict";
+Math.PI = 4;  // TypeError
+ +

傻了吧,报错了

+ +

全局变量undefined也是只读的, 所以你不能忽视臭名昭著的"undefined is not a function"错误:

+ +
"use strict";
+undefined = function () {};  // TypeError: "undefined" is read-only
+
+ +

下面这样都是有效,不报错的

+ +
"use strict";
+var obj = Object.freeze({name: "Score", points: 157});
+obj = {name: obj.name, points: 0};   // 用一个新对象替换原来的对象(其实就是更改了对象的指针)
+
+"use strict";
+var LUNG_COUNT = 2;  //
+LUNG_COUNT = 3;  //
+
+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/redeclared_parameter/index.html b/files/zh-cn/web/javascript/reference/errors/redeclared_parameter/index.html new file mode 100644 index 0000000000..9a53795180 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/redeclared_parameter/index.html @@ -0,0 +1,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 +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
SyntaxError: redeclaration of formal parameter "x" (Firefox)
+SyntaxError: Identifier "x" has already been declared (Chrome)
+SyntaxError: Cannot declare a let variable twice: 'x' (WebKit)
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

某个变量名称已经作为函数参数出现了,但是又使用了 let 在函数体里重声明了。在JavaScript 中不允许使用let在相同的函数或块范围内重新声明相同的变量。

+ +

示例

+ +

在本例中,参数 "arg" 又重新声明了:

+ +
function f(arg) {
+  let arg = "foo";
+}
+
+// SyntaxError: redeclaration of formal parameter "arg"
+
+ +

如果要更改函数体中的“arg”的值,可以像下面一样,但不需要再次声明同一个变量。 换句话说:你可以省略 let 关键字。 如果要创建一个新变量,则需要将其重命名,因为其与函数参数有冲突。

+ +
function f(arg) {
+  arg = "foo";
+}
+
+function f(arg) {
+  let bar = "foo";
+}
+
+ +

兼容性提醒

+ + + +

相关

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.html b/files/zh-cn/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.html new file mode 100644 index 0000000000..3d90929530 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.html @@ -0,0 +1,88 @@ +--- +title: 'TypeError: Reduce of empty array with no initial value' +slug: Web/JavaScript/Reference/Errors/Reduce_of_empty_array_with_no_initial_value +tags: + - Error + - JavaScript + - 参考 + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Reduce_of_empty_array_with_no_initial_value +--- +
{{jsSidebar("Errors")}}
+ +

消息

+ +
TypeError: reduce of empty array with no initial value
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出问题了?

+ +

在 JavaScript 中,有一些 reduce 函数:

+ + + +

这些函数有选择性的接收 initialValue (将会被用作回调函数第一次被调用的参数)。然而,如果没有初始值提供,它会用 {{jsxref("Array")}} 或 {{jsxref("TypedArray")}} 的第一个元素作为初始值。当提供一个空数组的时候这个错误会出现,因为那种情况下没有初始值被返回。

+ +

例子

+ +

无效的情况

+ +

当和过滤器({{jsxref("Array.prototype.filter()")}}、{{jsxref("TypedArray.prototype.filter()")}})结合使用的时候,可能会出现列表中所有元素被移除的情况。因此导致初始值为空。

+ +
var ints = [0, -1, -2, -3, -4, -5];
+ints.filter(x => x > 0)         // removes all elements
+    .reduce((x, y) => x + y)    // no more elements to use for the initial value.
+ +

类似的,当选择器中有瑕疵的时候相同的问题会发生,或者是列表中未预期的数量的元素:

+ +
var names = document.getElementsByClassName("names");
+var name_list = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + name);
+
+ +

有效的情况

+ +

这个问题有两种可能的解决办法:

+ +

一种是提供一个初始值作为操作符的中立元素,比如加法里的0,乘法里的1,或者是合并中的一个空字符串。

+ +
var ints = [0, -1, -2, -3, -4, -5];
+ints.filter(x => x < 0)         // removes all elements
+    .reduce((x, y) => x + y, 0) // the initial value is the neutral element of the addition
+
+ +

另一种办法是两方处理空的情况,要么在调用 reduce 之前,或者是在添加一个未预料的初始虚拟址后的回调函数中:

+ +
var names = document.getElementsByClassName("names");
+
+var name_list1 = "";
+if (names1.length >= 1)
+  name_list1 = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + name);
+// name_list1 == "" when names is empty.
+
+var name_list2 = Array.prototype.reduce.call(names, (acc, name) => {
+  if (acc == "") // initial value
+    return name;
+  return acc + ", " + name;
+}, "");
+// name_list2 == "" when names is empty.
+
+ +

另见

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/reserved_identifier/index.html b/files/zh-cn/web/javascript/reference/errors/reserved_identifier/index.html new file mode 100644 index 0000000000..d99acf3fa8 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/reserved_identifier/index.html @@ -0,0 +1,79 @@ +--- +title: 'SyntaxError: "x" is a reserved identifier' +slug: Web/JavaScript/Reference/Errors/Reserved_identifier +tags: + - JavaScript + - 语法错误 + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Reserved_identifier +--- +
{{jsSidebar("Errors")}}
+ +

消息提示

+ +
SyntaxError: "x" is a reserved identifier (Firefox)
+SyntaxError: Unexpected reserved word (Chrome)
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

保留字 用作标记符将会出错. 这些标记符在严格模式和非严格模式下保留:

+ + + +

以下标记符只会在严格模式下才作为保留字:

+ + + +

示例

+ +

严格与非严格模式下的保留字

+ +

在两种模式下,enum 标识符都会作为保留字。

+ +
var enum = { RED: 0, GREEN: 1, BLUE: 2 };
+// SyntaxError: enum is a reserved identifier
+
+ +

在严格模式下,会有更多的保留字。

+ +
"use strict";
+var package = ["potatoes", "rice", "fries"];
+// SyntaxError: package is a reserved identifier
+
+ +

你需要对上述变量重新命名。

+ +
var colorEnum = { RED: 0, GREEN: 1, BLUE: 2 };
+var list = ["potatoes", "rice", "fries"];
+ +

升级旧版本浏览器

+ +

假如你还在使用尚未支持 let 或 class 等特性的旧版本浏览器,你应该将它们升级到支持这些新语言特性的版本。

+ +
"use strict";
+class DocArchiver {}
+
+// SyntaxError: class is a reserved identifier
+//(只会在旧版本浏览器中抛出,例如 Firefox 44 或更老的版本)
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/resulting_string_too_large/index.html b/files/zh-cn/web/javascript/reference/errors/resulting_string_too_large/index.html new file mode 100644 index 0000000000..eaac0884fb --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/resulting_string_too_large/index.html @@ -0,0 +1,50 @@ +--- +title: 'RangeError: repeat count must be less than infinity' +slug: Web/JavaScript/Reference/Errors/Resulting_string_too_large +tags: + - Errors + - JavaScript + - RangeError + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Resulting_string_too_large +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
RangeError: repeat count must be less than infinity and not overflow maximum string size (Firefox)
+
+RangeError: Invalid count value (Chrome)
+
+ +

错误类型

+ +

{{jsxref("RangeError")}}

+ +

发生了什么?

+ +

代码中使用了 {{jsxref("String.prototype.repeat()")}}方法。它有一个计数参数,表示重复该字符串的次数。该参数必须在 0 及正 {{jsxref("Infinity")}} 之间,且不能为负数。该值的合法范围可以这样表示: [0, +∞)。

+ +

其结果字符串也不能长于最大字符串,不同 JavaScript 引擎中可能有所不同。 在 Firefox (SpiderMonkey) 里最大字符串大小为 228 -1 (0xFFFFFFF)。

+ +

示例

+ +

无效的

+ +
'abc'.repeat(Infinity); // RangeError
+'a'.repeat(2**28);      // RangeError
+
+ +

有效的

+ +
'abc'.repeat(0);    // ''
+'abc'.repeat(1);    // 'abc'
+'abc'.repeat(2);    // 'abcabc'
+'abc'.repeat(3.5);  // 'abcabcabc' (count will be converted to integer)
+
+ +

See also

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/stmt_after_return/index.html b/files/zh-cn/web/javascript/reference/errors/stmt_after_return/index.html new file mode 100644 index 0000000000..54fb1cf7a3 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/stmt_after_return/index.html @@ -0,0 +1,76 @@ +--- +title: 'Warning: unreachable code after return statement' +slug: Web/JavaScript/Reference/Errors/Stmt_after_return +tags: + - 警告 +translation_of: Web/JavaScript/Reference/Errors/Stmt_after_return +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
Warning: unreachable code after return statement (Firefox)
+
+ +

错误类型

+ +

警告

+ +

什么地方出错了?

+ +

return语句之后的不可达的语句会在下列情形中产生:

+ + + +

当一个表达式出现在一个有效的 return 表达式之后时,会出现这个警告,用以说明在 return 语句之后的表达式不可达,即这条语句之后的表达式永远不会运行。

+ +

为什么我需要在 return 语句之后添加分号?在省略分号的 return 语句之后,开发者想要终止当前函数的执行还是返回return之后表达式的结果的意图是不明确的。这个警告表明这种情况下 return 语句的表述具有二义性。

+ +

当在省略分号的return语句之后出现下列语句时,不会出现警告:

+ + + +

示例

+ +

无效的例子

+ +
function f() {
+  var x = 3;
+  x += 4;
+  return x;   // return 语句立即退出当前方法
+  x -= 3;     // 因而该语句从不会执行,即该语句为不可达语句
+}
+
+function f() {
+  return     // 这条语句被视作 `return;`
+    3 + 4;   // 因而此处该函数已经返回,该语句永不会执行
+}
+
+ +

合适的例子

+ +
function f() {
+  var x = 3;
+  x += 4;
+  x -= 3;
+  return x;  // OK: 执行完成所有语句之后返回
+}
+
+function f() {
+  return 3 + 4  // OK: 省略分号的 return 语句与执行的表达式在同一行
+}
+
+ +

相关页面

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/strict_non_simple_params/index.html b/files/zh-cn/web/javascript/reference/errors/strict_non_simple_params/index.html new file mode 100644 index 0000000000..3059705d88 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/strict_non_simple_params/index.html @@ -0,0 +1,113 @@ +--- +title: 'SyntaxError: "use strict" not allowed in function with non-simple parameters' +slug: Web/JavaScript/Reference/Errors/Strict_Non_Simple_Params +tags: + - Errors + - JavaScript + - SyntaxError + - TypeError + - use strict +translation_of: Web/JavaScript/Reference/Errors/Strict_Non_Simple_Params +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
Firefox:
+句法错误: "use strict" 不允许在带默认参数的函数中
+句法错误: "use strict" 不允许在带rest参数的函数中
+句法错误: "use strict" 不允许在带解构参数的函数中
+
+Chrome:
+句法错误: 非法的'use strict'指令,在带有非简单参数列表的函数中
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}.

+ +

哪里出错了?

+ +

在函数顶部直接写了 "use strict" ,而该函数拥有以下的参数其中之一:

+ + + +

根据ECMAScript规范,不允许在这些函数的顶部使用“use strict”指令。

+ +

示例

+ +

函数语句

+ +

在这种情况下,函数sum具有默认参数a = 1和b = 2:

+ +
function sum(a=1, b=2) {
+  // SyntaxError: "use strict" not allowed in function with default parameter
+  "use strict";
+  return a + b;
+}
+
+ +

如果这个函数应该处于 strict mode,并且整个脚本或封装函数也可以在严格模式下,可以移动 "use strict" 指令到函数之外:

+ +
"use strict";
+function sum(a=1, b=2) {
+  return a + b;
+}
+
+ +

函数表达式

+ +

函数表达式可以使用另一种解决方法:

+ +
var sum = function sum([a, b]) {
+  // SyntaxError: "use strict" not allowed in function with destructuring parameter
+  "use strict";
+  return a + b;
+};
+
+ +

这可以转换为以下表达式:

+ +
var sum = (function() {
+  "use strict";
+  return function sum([a, b]) {
+    return a + b;
+  };
+})();
+
+ +

箭头函数

+ +

如果箭头函数需要访问 this,则可以将箭头函数作为封闭函数来使用:

+ +
var callback = (...args) => {
+  // SyntaxError: "use strict" not allowed in function with rest parameter
+  "use strict";
+  return this.run(args);
+};
+
+ +

这可以转换为以下表达式:

+ +
var callback = (() => {
+  "use strict";
+  return (...args) => {
+    return this.run(args);
+  };
+})();
+
+ +

也可以看看

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/too_much_recursion/index.html b/files/zh-cn/web/javascript/reference/errors/too_much_recursion/index.html new file mode 100644 index 0000000000..1671a5598a --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/too_much_recursion/index.html @@ -0,0 +1,54 @@ +--- +title: 'InternalError: too much recursion' +slug: Web/JavaScript/Reference/Errors/Too_much_recursion +tags: + - InternalError + - recursion + - 内部错误 +translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
InternalError: too much recursion
+
+ +

错误类型

+ +

{{jsxref("InternalError","内部错误")}}.

+ +

什么地方出错了?

+ +

一个调用自身的函数被称作递归函数。一些情况下,递归函数类似于一个循环,都重复地执行一个代码段许多次,都需要一个条件(用于避免无尽循环或此处的无尽递归)。当出现过于深层的递归或无尽递归时,JavaScript将会抛出此错误。

+ +

示例

+ +

根据递归终止的条件,该函数将递归地执行 10 次。

+ +
function loop(x) {
+  if (x >= 10) // "x >= 10" 是递归终止条件
+    return;
+  // 进行一些操作...
+  loop(x + 1); // 递归调用
+}
+loop(0);
+ +

将递归条件设置为一个极大的数值,将不能运行:

+ +
function loop(x) {
+  if (x >= 1000000000000)
+    return;
+  // 进行一些操作...
+  loop(x + 1);
+}
+loop(0);
+
+// InternalError: too much recursion
+ +

相关页面

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/typed_array_invalid_arguments/index.html b/files/zh-cn/web/javascript/reference/errors/typed_array_invalid_arguments/index.html new file mode 100644 index 0000000000..314a4a425c --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/typed_array_invalid_arguments/index.html @@ -0,0 +1,76 @@ +--- +title: 'TypeError: invalid arguments' +slug: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +tags: + - JavaScript + - 类型错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Typed_array_invalid_arguments +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
TypeError: invalid arguments (Firefox)
+ +

错误类型

+ +

{{jsxref("TypeError")}}

+ +

哪里出错了?

+ +

类型化数组(Typed array) 的构造器可以通过接收以下类型的参数中的一种

+ + + +

来创建一个新的类型化数组。其他类型的构造器参数都无法创建合法的类型化数组。

+ +

示例

+ +

类型化数组——例如  {{jsxref("Uint8Array")}} ——无法通过字符串创建。实际上,字符串根本不能出现在类型化数组中。

+ +
var ta = new Uint8Array("nope");
+// TypeError: invalid arguments
+
+ +

创建一个合法的 {{jsxref("Uint8Array")}} 对象的不同方式:

+ +
// From a length
+var uint8 = new Uint8Array(2);
+uint8[0] = 42;
+console.log(uint8[0]); // 42
+console.log(uint8.length); // 2
+console.log(uint8.BYTES_PER_ELEMENT); // 1
+
+// From an array
+var arr = new Uint8Array([21,31]);
+console.log(arr[1]); // 31
+
+// From another TypedArray
+var x = new Uint8Array([21, 31]);
+var y = new Uint8Array(x);
+console.log(y[0]); // 21
+
+// From an ArrayBuffer
+var buffer = new ArrayBuffer(8);
+var z = new Uint8Array(buffer, 1, 4);
+
+// From an iterable
+var iterable = function*(){ yield* [1,2,3]; }();
+var uint8 = new Uint8Array(iterable);
+// Uint8Array[1, 2, 3]
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/undeclared_var/index.html b/files/zh-cn/web/javascript/reference/errors/undeclared_var/index.html new file mode 100644 index 0000000000..507da98563 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/undeclared_var/index.html @@ -0,0 +1,68 @@ +--- +title: 'ReferenceError: assignment to undeclared variable "x"' +slug: Web/JavaScript/Reference/Errors/Undeclared_var +tags: + - Errors + - JavaScript + - ReferenceError + - 严格模式 + - 错误 +translation_of: Web/JavaScript/Reference/Errors/Undeclared_var +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
ReferenceError: assignment to undeclared variable "x" (Firefox)
+ReferenceError: "x" is not defined (Chrome)
+ReferenceError: Variable undefined in strict mode (Edge)
+
+ +

错误类型

+ +

  仅在严格模式中出现 {{jsxref("ReferenceError")}} 警告。

+ +

发生了什么?

+ +

在代码里赋值了一个未声明的变量。换句话说,有处没有带着 var 关键字的赋值。事实上已声明的和未声明的变量之间有一些差异,这可能会导致意想不到的结果,这就是为什么 JavaScript 在严格模式打印出这种错误。

+ +

关于已声明和未声明的变量,其有三个注意事项:

+ + + +

更多信息及例子,请参考 var 页面。

+ +

关于未声明变量的赋值的错误仅在严格模式里出现。在非严格模式中,这些将被忽略。

+ +

示例

+ +

无效的

+ +

在本例中,"bar" 是未声明的变量。

+ +
function foo() {
+  "use strict";
+  bar = true;
+}
+foo(); // ReferenceError: assignment to undeclared variable bar
+
+ +

有效的

+ +

为了使 "bar" 是一个已声明变量,你需要在其前面加一个 var 关键字。

+ +
function foo() {
+  "use strict";
+  var bar = true;
+}
+foo();
+ +

相关

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/undefined_prop/index.html b/files/zh-cn/web/javascript/reference/errors/undefined_prop/index.html new file mode 100644 index 0000000000..9cda2d0501 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/undefined_prop/index.html @@ -0,0 +1,64 @@ +--- +title: 'ReferenceError: reference to undefined property "x"' +slug: Web/JavaScript/Reference/Errors/Undefined_prop +tags: + - Errors + - JavaScript + - ReferenceError + - Strict Mode + - 严格模式 +translation_of: Web/JavaScript/Reference/Errors/Undefined_prop +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
ReferenceError: reference to undefined property "x" (Firefox)
+
+ +

错误类型

+ +

仅在 strict mode 下出现 {{jsxref("ReferenceError")}} 警告。

+ +

哪里出错了?

+ +

脚本尝试去访问一个不存在的对象属性。property accessors 页面描述了两种访问属性的方法。

+ +

引用未定义属性的错误仅出现在 strict mode 代码中。在非严格代码中,对不存在的属性的访问将被忽略。

+ +

示例

+ +

无效的

+ +

本例中,bar 属性是未定义的,隐藏 ReferenceError 会出现。

+ +
"use strict";
+
+var foo = {};
+foo.bar; // ReferenceError: reference to undefined property "bar"
+
+ +

无效的

+ +

为了避免错误,您需要向对象添加 bar 的定义或在尝试访问 bar 属性之前检查 bar 属性的存在;一种检查的方式是使用 {{jsxref("Object.prototype.hasOwnProperty()")}} 方法。如下所示:

+ +
"use strict";
+
+var foo = {};
+
+// Define the bar property
+
+foo.bar = "moon";
+console.log(foo.bar); // "moon"
+
+// Test to be sure bar exists before accessing it
+
+if (foo.hasOwnProperty("bar") {
+  console.log(foo.bar);
+}
+ +

相关

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/unexpected_token/index.html b/files/zh-cn/web/javascript/reference/errors/unexpected_token/index.html new file mode 100644 index 0000000000..3de534c36a --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/unexpected_token/index.html @@ -0,0 +1,50 @@ +--- +title: 'SyntaxError: Unexpected token' +slug: Web/JavaScript/Reference/Errors/Unexpected_token +tags: + - Errors + - JavaScript + - SyntaxError +translation_of: Web/JavaScript/Reference/Errors/Unexpected_token +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
SyntaxError: expected expression, got "x"
+SyntaxError: expected property name, got "x"
+SyntaxError: expected target, got "x"
+SyntaxError: expected rest argument name, got "x"
+SyntaxError: expected closing parenthesis, got "x"
+SyntaxError: expected '=>' after argument list, got "x"
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

期望获得一个特定的语法结构,但得到了其他的。 可能只是一个简单的错字。

+ +

示例

+ +

期望的表达式

+ +

例如,在调用函数时,不允许使用尾随逗号。 有尾逗号的时候,JavaScript 会期望有另一个参数,可以是任何表达式。

+ +
Math.max(2, 42,);
+// SyntaxError: expected expression, got ')'
+
+ +

正确的方法是省略最后一个逗号或添加另一个参数:

+ +
Math.max(2, 42);
+Math.max(2, 42, 13+37);
+
+ +

相关

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/unexpected_type/index.html b/files/zh-cn/web/javascript/reference/errors/unexpected_type/index.html new file mode 100644 index 0000000000..c90cb20c27 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/unexpected_type/index.html @@ -0,0 +1,65 @@ +--- +title: 'TypeError: "x" is (not) "y"' +slug: Web/JavaScript/Reference/Errors/Unexpected_type +tags: + - 类型错误 +translation_of: Web/JavaScript/Reference/Errors/Unexpected_type +--- +
{{jsSidebar("Errors")}}
+ +

消息

+ +
TypeError: "x" is (not) "y"
+
+Examples:
+TypeError: "x" is undefined
+TypeError: "x" is null
+TypeError: "undefined" is not an object
+TypeError: "x" is not an object or null
+TypeError: "x" is not a symbol
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}.

+ +

什么地方出错了?

+ +

出现了与期望不符的类型。 这个错误常常由 {{jsxref("undefined")}} 或 {{jsxref("null")}} 值引起。

+ +

此外,某些方法,例如 {{jsxref("Object.create()")}} 或 {{jsxref("Symbol.keyFor()")}}, 要求必须提供特定类型的参数。

+ +

示例

+ +

错误情形

+ +
// undefined and null cases on which the substring method won't work
+var foo = undefined;
+foo.substring(1); // TypeError: foo is undefined
+
+var foo = null;
+foo.substring(1); // TypeError: foo is null
+
+
+// Certain methods might require a specific type
+var foo = {}
+Symbol.keyFor(foo); // TypeError: foo is not a symbol
+
+var foo = 'bar'
+Object.create(foo); // TypeError: "foo" is not an object or null
+
+ +

解决方法

+ +

要解决空指针以及 undefinednull 值的问题, 你可以使用 typeof 操作符, 例如:

+ +
if (typeof foo !== 'undefined') {
+  // Now we know that foo is defined, we are good to go.
+}
+ +

相关页面

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/unnamed_function_statement/index.html b/files/zh-cn/web/javascript/reference/errors/unnamed_function_statement/index.html new file mode 100644 index 0000000000..83d147aaab --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/unnamed_function_statement/index.html @@ -0,0 +1,114 @@ +--- +title: 'SyntaxError: function statement requires a name' +slug: Web/JavaScript/Reference/Errors/Unnamed_function_statement +tags: + - JavaScript + - 语法错误 + - 错误提示 +translation_of: Web/JavaScript/Reference/Errors/Unnamed_function_statement +--- +
{{jsSidebar("Errors")}}
+ +

错误提示

+ +
SyntaxError: function statement requires a name [Firefox]
+SyntaxError: Unexpected token ( [Chrome]
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}}

+ +

哪里出错了?

+ +

函数声明需要提供函数名称。你需要检查函数是如何定义的,是否需要为其提供名称,出现问题的函数是否需要声明为函数表达式或立即调用函数表达式({{Glossary("IIFE")}}),以及函数在上下文环境中出现的位置是否正确。

+ +

示例

+ +

语句与表达式

+ +

函数语句(或函数声明)需要命名,以下写法是不正确的:

+ +
function () {
+  return 'Hello world';
+}
+// SyntaxError: function statement requires a name
+
+ +

你可以使用函数表达式(赋值)来代替:

+ +
var greet = function() {
+  return 'Hello world';
+};
+ +

者是你想将其作为立即调用函数表达式(IIFE,Immediately Invoked Function Expression),也就是定义后立即执行的函数。在这种情况下你需要用到更多的括号:

+ +
(function () {
+
+})();
+ +

标号函数(Labeled functions)

+ +

你使用函数标号(labels)的时候, 也需要在关键词 function 后面提供一个函数名称. 这样的代码是不能运行的:

+ +
function Greeter() {
+  german: function () {
+    return "Moin";
+  }
+}
+// SyntaxError: function statement requires a name
+
+ +

这个例子可以正常运行:

+ +
function Greeter() {
+  german: function g() {
+    return "Moin";
+  }
+}
+ +

对象方法

+ +

如果你想创建创建一个对象方法,那么需要首先创建一个对象。以下语法(function 关键字后面没有提供名称)是合法的:

+ +
var greeter = {
+  german: function () {
+    return "Moin";
+  }
+};
+ +

回调函数的语法

+ +

另外,如果使用到了回调函数,那么检查一下语法是否正确。大括号与逗号很容易使情况变糟。

+ +
promise.then(
+  function() {
+    console.log("success");
+  });
+  function() {
+    console.log("error");
+}
+// SyntaxError: function statement requires a name
+
+ +

正确的形式应该是这样的:

+ +
promise.then(
+  function() {
+    console.log("success");
+  },
+  function() {
+    console.log("error");
+  }
+);
+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/unterminated_string_literal/index.html b/files/zh-cn/web/javascript/reference/errors/unterminated_string_literal/index.html new file mode 100644 index 0000000000..b0ab684413 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/unterminated_string_literal/index.html @@ -0,0 +1,67 @@ +--- +title: 'SyntaxError: unterminated string literal' +slug: Web/JavaScript/Reference/Errors/Unterminated_string_literal +tags: + - Error + - JavaScript + - SyntaxError +translation_of: Web/JavaScript/Reference/Errors/Unterminated_string_literal +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
SyntaxError: unterminated string literal
+
+ +

错误类型

+ +

{{jsxref("SyntaxError")}} 

+ +

哪里出错了?

+ +

某处 js 解析字符串出错。字符串必须使用单引号或双引号来正确的关闭。在 Javascript 中使用单引号的字符和双引号的字符串是没有区别的。字符串用转义字符不是单引号就是双引。为解决这个错误,检查一下:

+ + + +

示例

+ +

多行字符串

+ +

在javascript中你不能够直接使用多行字符串赋值给一个变量。如下:

+ +
var longString = "This is a very long string which needs
+                  to wrap across multiple lines because
+                  otherwise my code is unreadable.";
+// SyntaxError: unterminated string literal
+ +

可以使用"+"运算符,反斜杠,或模板字符串来代替多行。“+”运算符的使用如下:

+ +
var longString = "This is a very long string which needs " +
+                 "to wrap across multiple lines because " +
+                 "otherwise my code is unreadable.";
+
+ +

或者你可以使用“\”在每一行的末尾,以表示该字符串在下一行继续。要确保“\“之后没有没有空格和任何其他的字符,及缩进,否则该“\”将不会起作用。使用方法如下:

+ +
var longString = "This is a very long string which needs \
+to wrap across multiple lines because \
+otherwise my code is unreadable.";
+
+ +

另一种方式是使用 ES 2015 的环境所支持模板字符串(反引号` `)。

+ +
var longString = `This is a very long string which needs
+                  to wrap across multiple lines because
+                  otherwise my code is unreadable.`;
+ +

相关

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/var_hides_argument/index.html b/files/zh-cn/web/javascript/reference/errors/var_hides_argument/index.html new file mode 100644 index 0000000000..01aa0260fe --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/var_hides_argument/index.html @@ -0,0 +1,51 @@ +--- +title: 'TypeError: variable "x" redeclares argument' +slug: Web/JavaScript/Reference/Errors/Var_hides_argument +translation_of: Web/JavaScript/Reference/Errors/Var_hides_argument +--- +
{{jsSidebar("Errors")}}
+ +

消息

+ +
TypeError: variable "x" redeclares argument (Firefox)
+
+ +

错误类型

+ +

{{jsxref("TypeError")}} 警告仅仅在 严格模式下 出现。

+ +

哪里有问题?

+ +

函数参数中出现了名称相同的变量,之后在函数体中使用 var 赋值语句重新声明。 这可能是一个命名冲突,所以 JavaScript 警告了它。

+ +

这个错误只在 严格模式的代码 中作为警告出现。在非严格模式的代码中,重新声明会被忽略。

+ +

示例

+ +

无效情况

+ +

这个例子中,变量 arg 重新声明了参数。

+ +
"use strict";
+
+function f(arg) {
+  var arg = "foo";
+}
+
+ +

无效情况

+ +

为了修复警告,var 语句应该被移除,因为变量已经存在。或者,你可以重命名函数参数或者变量名称。

+ +
"use strict";
+
+function f(arg) {
+  arg = "foo";
+}
+
+ +

另见

+ + diff --git "a/files/zh-cn/web/javascript/reference/errors/\344\270\215\350\203\275\346\267\273\345\212\240\345\261\236\346\200\247/index.html" "b/files/zh-cn/web/javascript/reference/errors/\344\270\215\350\203\275\346\267\273\345\212\240\345\261\236\346\200\247/index.html" new file mode 100644 index 0000000000..cceeb330c4 --- /dev/null +++ "b/files/zh-cn/web/javascript/reference/errors/\344\270\215\350\203\275\346\267\273\345\212\240\345\261\236\346\200\247/index.html" @@ -0,0 +1,52 @@ +--- +title: 'TypeError: can''t assign to property "x" on "y": not an object' +slug: Web/JavaScript/Reference/Errors/不能添加属性 +translation_of: Web/JavaScript/Reference/Errors/Cant_assign_to_property +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
TypeError: can't assign to property "x" on {y}: not an object (Firefox)
+TypeError: Cannot create property 'x' on {y} (Chrome)
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}.

+ +

原因

+ +

在 {{jsxref("Strict_mode")}}下, 当试图给一个{{Glossary("symbol")}},{{Glossary("string")}},{{Glossary("number")}}或者一个{{Glossary("boolean")}}类型的数据创建一个属性时就会报 {{jsxref("TypeError")}}, 任何 {{Glossary("Primitive")}} 值都不允许有{{Glossary("property/JavaScript", "property")}}.

+ +

这个问题可能是由一个错误的值被放在了一个错误的地方导致的, 或者预期{{jsxref("String")}}或{{jsxref("Number")}}的对象变体

+ +

 

+ +

示例

+ +

错误的情况

+ +
'use strict';
+
+var foo = "my string";
+// 下面这行代码在非严格模式下不会执行.
+foo.bar = {}; // TypeError: can't assign to property "bar" on "my string": not an object
+
+ +

如何正确使用

+ +

有两种方式, 第一种修复这部分代码阻止{{Glossary("primitive")}}被用于这种情况, 或者可以通过使用对象构造器创建来修复.

+ +
'use strict';
+
+var foo = new String("my string");
+foo.bar = {};
+
+ +

页面相关

+ + -- cgit v1.2.3-54-g00ecf