This question already has an answer here:
这个问题在这里已有答案:
- Why doesn't a Javascript return statement work when the return value is on a new line? 3 answers
- 当返回值在新行上时,为什么Javascript返回语句不起作用? 3个答案
I'm trying call a function, from a module, to build a HTML string. When the function is written in the below way, with a LF(Line Feed) between the return statement and the string declaration, the return is "undefined"...
我正在尝试从模块调用函数来构建HTML字符串。当函数以下面的方式写入时,在return语句和字符串声明之间使用LF(换行符),返回是“未定义的”...
exports.buildHtmlContent = function (content) {
return
"<!DOCTYPE html> \
\n<html lang='en-US'> \
\n <head> \
\n </head> \
\n <body> \
\n <h1>" + content + "</h1> \
\n </body> \
\n</html>";
};
However, when the function is written in this other below way, without the LF after return statement, it works properly!
但是,当函数以下面的方式写入,在返回语句后没有LF,它可以正常工作!
exports.buildHtmlContent = function (content) {
return "<!DOCTYPE html> \
\n<html lang='en-US'> \
\n <head> \
\n </head> \
\n <body> \
\n <h1>" + content + "</h1> \
\n </body> \
\n</html>";
};
This is a bug in NodeJs? The NodeJs interpretation from the function 1 looks like it thinks the return is empty, even with the miss of ";", and didn't correlate the below string declaration with the return statement. Apparently NodeJs didn't check the miss of ";" before decide that is the interpretation end of the "return" statement.
这是NodeJs中的一个错误?函数1中的NodeJs解释看起来像是认为返回为空,即使缺少“;”,并且没有将下面的字符串声明与return语句相关联。显然NodeJ没有检查错过“;”在决定是“返回”声明的解释结束之前。
1 个解决方案
#1
3
This has to do with JavaScript, and not Node.js specifically. Most JavaScript engines implement Automatic Semi-colon Insertion, meaning that it will try to automatically separate two clauses with a semi-colon. The statement return
on its own is valid, as it will return undefined
, and a string is a valid statement as well. For example:
这与JavaScript有关,而不是与Node.js有关。大多数JavaScript引擎实现自动半冒号插入,这意味着它将尝试使用分号自动分隔两个子句。语句返回本身是有效的,因为它将返回undefined,并且字符串也是有效的语句。例如:
"use strict";
The reason why ASI is triggered is due to both the line break, and return
being a restricted production. Not a bug, but a feature.
触发ASI的原因是由于换行和返回都是限制生产。不是错误,而是一个功能。
#1
3
This has to do with JavaScript, and not Node.js specifically. Most JavaScript engines implement Automatic Semi-colon Insertion, meaning that it will try to automatically separate two clauses with a semi-colon. The statement return
on its own is valid, as it will return undefined
, and a string is a valid statement as well. For example:
这与JavaScript有关,而不是与Node.js有关。大多数JavaScript引擎实现自动半冒号插入,这意味着它将尝试使用分号自动分隔两个子句。语句返回本身是有效的,因为它将返回undefined,并且字符串也是有效的语句。例如:
"use strict";
The reason why ASI is triggered is due to both the line break, and return
being a restricted production. Not a bug, but a feature.
触发ASI的原因是由于换行和返回都是限制生产。不是错误,而是一个功能。