我需要使以下大型 if 语句在 JavaScript 中更具可读性。
有什么想法吗?
if ( Tools.Array.contains( that.pAutocompleteAliasUsed[i], this.currentString) !== false &&
( this.autocomplete.list.length === 0 ) || ( this.currentString.toLowerCase() !== this.autocomplete.list[0].target.alias.toLowerCase() ) )
{
make something
}
最佳答案
为了提高可读性,您可以做的一件事是从 if 语句中提取各种逻辑测试。阅读单个语句然后在 if 测试中很好地命名 bool 参数要容易得多。
我已经为这个例子中的第一个测试做了这个,我和其他人一起尝试过,但是你可以给他们起比我更好的名字,因为你知道他们在测试什么。
var toolsContainsString = Tools.Array.contains(that.pAutocompleteAliasUsed[i], this.currentString) !== false;
var isAutoCompleteEmpty = this.autocomplete.list.length === 0;
var isTargetMatch = this.currentString.toLowerCase() !== this.autocomplete.list[0].target.alias.toLowerCase();
if (toolsContainsString && (isAutoCompleteEmpty || isTargetMatch)) {
//make something
}
关于javascript - 如何使这个大的 if 语句在 JavaScript 中更具可读性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8325182/