网络编程
位置:首页>> 网络编程>> JavaScript>> JavaScript程序编码规范[译](4)

JavaScript程序编码规范[译](4)

作者:cloudwater  发布时间:2009-07-20 17:54:00 

标签:JavaScript,编程,规范

if 语句

if语句应如以下格式:

if (condition){
statements;
}
if (condition) {
statements;
} else {
statements;
}
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}

for 语句

for语句应如以下格式:

for (initialization;condition ; update) {
statements;
}
for (variable in object)if (filter) {
statements;
}

第一种形式的循环用于已经知道相关参数的数组循环。

第二种形式应用于对象中。object原型中的成员将会被包含在迭代器中。通过预先定义hasOwnProperty方法来区分真正的 object成员是个不错方法:

for (variablein object) if (object.hasOwnProperty(variable )){
statements;
}

while 语句

while语句应如以下格式:

while (condition){
statements;
}

do 语句

do语句应如以下格式:

do {
statements;
} while (condition);

不像别的复合语句,do语句总是以;(分号)结尾。

switch 语句

switch语句应如以下格式:

switch (expression){
case expression:
statements;
default:
statements;
}

每个 case与switch对齐。这可避免过分缩进。

每一组statements(除了default应以 break,return,或者throw结尾。不要让它顺次往下执行。

try 语句

try语句应如以下格式:

try {
statements;
} catch (variable){
statements;
}
try {
statements;
} catch (variable){
statements;
} finally {
statements;
}

continue 语句

避免使用continue语句。它很容易使得程序的逻辑过程晦涩难懂。

with 语句

不要使用with语句。

空白

用空行来将逻辑相关的代码块分割开可以提高程序的可读性。

空格应在以下情况时使用:

* 跟在((左括号)后面的关键字应被一个空格隔开。


while (true) {

* 函数参数与((左括号)之间不应该有空格。这能帮助区分关键字和函数调用。
* 所有的二元操作符,除了.(点) 和((左括号)和 [(左方括号)应用空格将其与操作数隔开。
* 一元操作符与其操作数之间不应有空格,除非操作符是个单词,比如typeof。
* 每个在控制部分,比如for 语句中的; (分号)后须跟一个空格。
* 每个,(逗号)后应跟一个空格。

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com