避免else
并利用早期的return
可以防止代码变得太深嵌套。哪个示例看起来更可读?
function doStuff (thing) {
if (thing.foo) {
alert ("thing.foo is alive and well");
if (thing.foo.bar) {
alert ("thing.foo.bar is alive and well");
if (thing.foo.bar.baz) {
alert ("thing.foo.bar.baz is alive and well");
// TODO: stuff with thing.foo.bar.baz
} else {
alert ("thing.foo.bar.baz doesn't exist!");
}
} else {
alert ("thing.foo.bar doesn't exist!");
}
} else {
alert ("thing.foo doesn't exist!");
}
}
或
function doStuff (thing) {
if (!thing.foo) {
alert ("thing.foo doesn't exist!");
return;
}
alert ("thing.foo is alive and well");
if (!thing.foo.bar) {
alert ("thing.foo.bar doesn't exist!");
return;
}
alert ("thing.foo.bar is alive and well");
if (!thing.foo.bar.baz) {
alert ("thing.foo.bar.baz doesn't exist!");
return;
}
alert ("thing.foo.bar.baz is alive and well");
// TODO: stuff with thing.foo.bar.baz
}
...我觉得第二个是更可读!
您使用哪种语言? – ChaosPandion 2010-07-12 23:40:40