关于Javascript中的三目运算

来源:互联网 发布:电脑软件乱码修复 编辑:程序博客网 时间:2024/05/08 08:31

现有如下代码,先不管要干什么,利用三目运算可以大大的简写一下一大堆代码...
                        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;

 

 

 

原创粉丝点击