The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
(function(){varlower=10,upper=17,current=14;// 单位递增functionnext(){if(current<upper){current+=1;}else{current=lower;}returncurrent;}// 单位递减functionprev(){if(current>lower){current-=1;}else{current=upper;}returncurrent;}console.log(next());// current = 15console.log(next());// current = 16console.log(next());// current = 17console.log(next());// current = 10}());
利用取余运算符%,我们可以将如上代码简化为如下(注意此时没有了if条件语句):
1234567891011121314151617181920
(function(){varlower=10,upper=17,dist=upper-lower+1,current=14;functionnext(){return(current=lower+(current-lower+1+dist)%dist);}functionprev(){return(current=lower+(current-lower-1+dist)%dist);}console.log(prev());// current = 13console.log(prev());// current = 12console.log(prev());// current = 11console.log(prev());// current = 10console.log(prev());// current = 17}());