JavaScript和Python中的分号有什么区别? [英] What is the difference between semicolons in JavaScript and in Python?
问题描述
Python和JavaScript都允许开发人员使用或省略分号.但是,我经常看到它(在书和博客中)建议我不应该在Python中使用分号,而应该始终在JavaScript中使用分号.
Python and JavaScript both allow developers to use or to omit semicolons. However, I've often seen it suggested (in books and blogs) that I should not use semicolons in Python, while I should always use them in JavaScript.
语言在使用分号之间有技术上的区别吗?还是仅仅是文化上的区别?
Is there a technical difference between how the languages use semicolons or is this just a cultural difference?
推荐答案
Python中的分号是完全可选的(当然,除非您想在一行中包含多个语句).我个人认为,每条语句末尾带有分号的Python代码看起来非常难看.
Semicolons in Python are totally optional (unless you want to have multiple statements in a single line, of course). I personally think Python code with semicolons at the end of every statement looks very ugly.
现在在Javascript中,如果您不写分号,则会在行尾自动插入 1 .这可能会导致问题.考虑:
Now in Javascript, if you don't write a semicolon, one is automatically inserted1 at the end of line. And this can cause problems. Consider:
function add(a, b) {
return
a + b
}
您可能会认为这会返回 a + b
,但是Javascript却使您不胜其烦,并将其视为:
You'd think this returns a + b
, but Javascript just outsmarted you and sees this as:
function add() {
return;
a + b;
}
改为返回 undefined
.
1 See page 27, item 7.9 - Automatic Semicolon Insertion on ECMAScript Language Specification for more details and caveats.
这篇关于JavaScript和Python中的分号有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!