+ -
当前位置:首页 → 问答吧 → 【100分】关于这小段js该怎么优化比较好?

【100分】关于这小段js该怎么优化比较好?

时间:2011-10-04

来源:互联网

if else太冗长了,有什么好方法可以优化下吗?自己想了好久没想出来。
JScript code

            Move:function(){
                var p = arguments[0];
                var mark = p.getAttribute("mark").split("=");
                var i = parseInt(mark[0]);
                var j = parseInt(mark[1]);
                var direction,time,distance;
                if(j+1<this.mapSizeX&&this.Map[i][j+1]=="no"){
                    direction="rightleft";
                    distance=this.imgWidth;
                    this.Map[i][j+1]=this.Map[i][j];
                    this.Map[i][j]="no";
                    j=j+1;
                }
                else if(j-1>=0&&this.Map[i][j-1]=="no"){
                    direction="rightleft";
                    distance=-this.imgWidth;
                    this.Map[i][j-1]=this.Map[i][j];
                    this.Map[i][j]="no";
                    j=j-1
                }
                else if(i+1<this.mapSizeY&&this.Map[i+1][j]=="no"){
                    direction="bottomtop";
                    distance=this.imgHeight;
                    this.Map[i+1][j]=this.Map[i][j];
                    this.Map[i][j]="no";
                    i=i+1
                }
                else if(i-1>=0&&this.Map[i-1][j]=="no"){
                    direction="bottomtop";
                    distance=-this.imgHeight;
                    this.Map[i-1][j]=this.Map[i][j];
                    this.Map[i][j]="no";
                    i=i-1
                }
                this.Change(p,direction,distance,i,j);
                this.PrintMap();
            },

作者: wuyql1   发布时间: 2011-10-04

你呀,真是的
将这个if ........else
修改成
switch(变量)
{
  case 值1:
  {
  }
  case 值2:
  {
  }
  default:
  {
  }
}

作者: sgzhou12345   发布时间: 2011-10-04

给分吧

作者: sgzhou12345   发布时间: 2011-10-04

引用 1 楼 sgzhou12345 的回复:
你呀,真是的
将这个if ........else
修改成
switch(变量)
{
case 值1:
{
}
case 值2:
{
}
default:
{
}
}

= =#
i 服了 you

作者: wuyql1   发布时间: 2011-10-04

这小段代码里面的代码很多地方相似,这样太长了。怎么优化让它少点呢。

作者: wuyql1   发布时间: 2011-10-04

 

  把变得值 封装成参数 

 传到一个函数里面, 然后要 返回一个数组 ..

 我说的是这段  

 direction="bottomtop";
  distance=-this.imgHeight;
  this.Map[i-1][j]=this.Map[i][j];
  this.Map[i][j]="no";
  i=i-1

作者: qianzai5765638   发布时间: 2011-10-04