關於Javascript中的三目運算

現有如下代碼,先不管要幹什麼,利用三目運算可以大大的簡寫一下一大堆代碼...
                        if (result.d.length === 6)
                        {
                            ShowPlayReadyNow(1, result.d[0]);
                        }

                       else if (result.d.length === 12)
                        {
                      
                            ShowPlayReadyNow(1, result.d[0]);
                            ShowPlayReadyNow(2,  result.d[6]);
                        }
                        else if (result.d.length === 18)
                        {
                            ShowPlayReadyNow(1,  result.d[0]);
                            ShowPlayReadyNow(2,  result.d[6]);
                            ShowPlayReadyNow(0,  result.d[12]);
                        }


可以簡寫爲:

result.d.length === 6?ShowPlayReadyNow(1, result.d[0])

                                  :result.d.length === 12?[ShowPlayReadyNow(1, result.d[0]),ShowPlayReadyNow(2,  result.d[6]),]:result.d.length === 18

                                 ?[ShowPlayReadyNow(1,  result.d[0]), ShowPlayReadyNow(2,  result.d[6]),ShowPlayReadyNow(0,  result.d[12])]

                                 :null;

 

其實也沒什麼,不過當類似於上面的代碼多的時候,用這種寫法個人感覺還是不錯的,另外在js的三目運算中

a==1?say():null 這樣是可以的

a==1?function(){}:null 錯誤 ...不能寫匿名函數

 

當然如果需要執行多個方法的時候可以以數組的形式講方法傳入即可

 

a==1?[Chi(),He()]:null;

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章