12

我做了一些谷歌搜索,但我得到了与编码字符串或文件相关的结果。

我可以用 UTF-8编写我的 Node.js JavaScript 源代码吗?我可以在注释、字符串或变量名中使用非 ASCII 字符吗?

ECMA-262 似乎需要 UTF-16 encoding,但 Node.js 不会运行 UTF-16 编码.js文件。但是,它将运行 UTF-8 源代码并正确解释非 ASCII 字符。

那么这是设计使然还是“意外”?是否在某处指定支持 UTF-8 源代码?

4

2 回答 2

0

参考: http: //mathiasbynens.be/notes/javascript-identifiers

UTF-8 字符是有效的 JavaScript 变量名。继续并编码 UTF-8。

于 2012-04-12T14:14:51.307 回答
-1

我找不到说明 Node 将文件视为以 UTF-8 编码的文档,但在实验上似乎是这样:

/* Check in your editor that this Javascript file was saved in UTF-8 */
var nonEscaped = "Планета_Зямля";
var escaped = "\u041f\u043b\u0430\u043d\u0435\u0442\u0430\u005f\u0417\u044f\u043c\u043b\u044f";
if (nonEscaped === escaped) {
  console.log("They match");
}

上面的示例打印They match.

非 BMP 注释:

请注意,UTF-8 支持非 BMP 代码点(U+10000 及以上),但 Javascript 在这种情况下会很复杂,它会自动将它们转换为代理对。这是语言的一部分:

/* Check in your editor that this Javascript file was saved in UTF-8 */
var nonEscaped = ""; // U+1F4A9
var escaped1 = "\ud83d\udca9";
if (nonEscaped === escaped1) {
  console.log("They match");
}
/* Newer implementations support this syntax: */
var escaped2 = "\u{1f4a9}";
if (nonEscaped === escaped2) {
   console.log("The second string matches");
}

这打印They matchThe second string matches.

于 2015-09-11T16:58:02.740 回答