[英]Correct JavaScript IF Else Syntax
我正在更新現有的JavaScript應用程序。 此更新的一部分涉及更好地格式化和清理代碼。
現在這是使用if()
和else
語句而沒有所有正確括號的函數之一......當人們使用這種簡寫方法時,我個人討厭它,當他們混合它並且有時使用它時更加如此其他。 下面的示例代碼就是這種情況。
this.setFlags = function() {
if (document.documentElement)
this.dataCode = 3;
else
if (document.body && typeof document.body.scrollTop != 'undefined')
this.dataCode = 2;
else
if (this.e && this.e.pageX != 'undefined')
this.dataCode = 1;
this.initialised = true;
}
老實說,我不知道如何正確地將括號添加到此功能,下面是我所擁有的,但我認為它可能不正確。 JavaScript專家可以告訴我嗎?
this.setFlags = function() {
if (document.documentElement){
this.dataCode = 3;
}else{
if (document.body && typeof document.body.scrollTop != 'undefined'){
this.dataCode = 2;
}else{
if (this.e && this.e.pageX != 'undefined'){
this.dataCode = 1;
}
}
}
this.initialised = true;
}
我同意你不喜歡沒有括號的if/else
語句。 你的包圍似乎對我來說是正確的。 但是,有一種更簡單的方法:
this.setFlags = function() {
if (document.documentElement) {
this.dataCode = 3;
} else if (document.body && typeof document.body.scrollTop != 'undefined') {
this.dataCode = 2;
} else if (this.e && this.e.pageX != 'undefined') {
this.dataCode = 1;
}
this.initialised = true;
}
正如Dave Chen在評論中指出的那樣,由於if/else
分支的簡單性和並行性 - 它們都為this.dataCode
賦值 - 你也可以使用嵌套的三元運算符:
this.setFlags = function() {
this.dataCode = document.documentElement ? 3
: document.body
&& typeof document.body.scrollTop != 'undefined' ? 2
: this.e && this.e.pageX != 'undefined' ? 1
: this.dataCode;
this.initialised = true;
}
這樣做的好處是更清楚的是,所有條件都只是確定要分配給this.dataCode
值。 缺點(在我看來是一個很大的缺點)是除非嵌套的三元運算符以謹慎的方式進行格式化(例如我在這里所做的),否則在沒有仔細研究表達式的情況下,基本上不可能知道發生了什么。 不幸的是,我熟悉的大多數JavaScript代碼格式化程序在格式化這些表達式(或保留這種格式)方面做得很差。 (有趣的是,我使用的幾個Perl格式化程序做得很好。但這不是Perl。)
這是正確的,但你可以使它更整潔:
this.setFlags = function() {
if (document.documentElement) {
this.dataCode = 3;
} else if (document.body && typeof document.body.scrollTop != 'undefined') {
this.dataCode = 2;
} else if (this.e && this.e.pageX != 'undefined') {
this.dataCode = 1;
}
this.initialized = true;
};
哦,這已經發布了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.