什么时候使用分号合适? [英] When is it appropriate to use a semicolon?
问题描述
我知道JavaScript(因此是TypeScript)在许多情况下都支持省略分号。不过,我想按照 TypeScript深入研究中的建议添加分号
I know that JavaScript (and thus TypeScript) support the omission of semicolons in many cases. Nevertheless I want to add semicolons to be unambiguous as suggested in TypeScript Deep Dive
但是我找不到列出使用分号的指南。例如,看下面的代码
However I cannot find a guide that lists where to use semicolon. For example look at the following code
class Person {
private name: string; // A
constructor(name: string) {
this.name = name;
}; // B
public add = () => {
return "C";
}; // C
}; // D
我相当确定在 A 上使用分号。但是 B , C , D 和我的示例未涵盖的所有其他情况呢?
I'm fairly sure to use a semicolon at A. But what about B, C, D and all the other cases not covered by my example?
我不是问在哪里省略分号,而是在哪里添加它们。像 always 这样的答案不能满足我的需求,因为我不能在 public
之后添加;
。我想知道确切在哪里放置分号。
I'm not asking where to omit semicolon but where to add them. An answer like always does not fulfill my needs since I cannot add a ;
after public
. I want to know where exactly to put semicolon.
推荐答案
仅以 [
,(
或带有分号的`,并且您(几乎)是黄金**
使用与另一个答案相同的示例:
Just prefix lines starting with [
, (
, or ` with a semicolon and you're (almost) golden*
Using the same example as another answer:
var x = { xx : "hello", yy : "world"}
(function () {
console.log("Hello World");
})();
我们根据以下规则添加分号:
We add a semicolon according to this rule:
var x = { xx : "hello", yy : "world"}
;(function () {
否则javascript认为我们正在尝试调用(
一些函数,或 reference [
一些数组。这更简单,易于理解,并且您还需要在中为
循环使用分号,但是 .forEach
方法是更干净,更轻松的方法。我很自信地说这条规则涵盖了您在javascript / typescript中使用分号所需的99%的情况。
otherwise javascript thinks we're trying to call(
some function, or reference[
some array. This is simpler, easier to follow, and it's visually easier to spot. You also need semicolons in for
loops, but the .forEach
method is a cleaner and easier method. I'd confidently say this one rule covers 99% of the scenarios you need to use a semicolon in javascript/typescript.
遵循此方法,
return
7
返回后,有一个换行符,浏览器插入一个分号,终止语句,如下所示:
After return, there's a newline, and the browser inserts a semicolon, terminating the statement like this:
return; // this will return undefined.
7
执行以下操作:
Do this instead:
return (
7
)
使用分号的Javascript实际上非常聪明,有一个开放的括号,因此在找到结束括号之前不会插入分号。
Javascript is actually pretty smart with semicolons, there's an open paren, so no semicolon is inserted until the closing paren is found.
如果您习惯放分号无处不在,并且不确切知道何时需要分号,您可以阅读长达几页的说明: http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding
If you have a habit of putting semicolons everywhere and not knowing exactly when they are needed, you could read this for a several page long explanation: http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding
我承认大多数人在每一行的末尾仍然会乱扔半冒号,但是如果您是新手并且只是学习,这是更好的方法。
I admit most people will still just litter semi colons at the end of every line, but if you're new and just learning, this is the better approach.
这篇关于什么时候使用分号合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!