Javascript 用更简洁的逻辑替换switch语句
我有一段代码,比如Javascript 用更简洁的逻辑替换switch语句,javascript,algorithm,optimization,Javascript,Algorithm,Optimization,我有一段代码,比如 switch (newDir) { case "left": { this.dx = -1; this.dy = 0; break; } case "up": { this.dx =
switch (newDir)
{
case "left":
{
this.dx = -1; this.dy = 0;
break;
}
case "up":
{
this.dx = 0; this.dy = 1;
break;
}
case "right":
{
this.dx = 1; this.dy = 0;
break;
}
case "down":
{
this.dx = 0; this.dy = -1;
break;
}
default: // never happens
break;
}
这意味着设置游戏中某个对象移动的方向。我认为它可读性很好,不言自明,但它太大了,我不喜欢。我想知道你们是否知道我可以用什么方法来巩固它
this.dx = ... ;
this.dy = ... ;
可能是涉及位运算符或映射之类的东西。将对象用作映射
var directions = {
'left': {
dx : -1, dy : 0
},
'right': {
dx : 1, dy : 0
},
'up': {
dx : 0, dy : 1
},
'down': {
dx : 0, dy : -1
}
};
this.dx = directions[newDir].dx;
this.dy = directions[newDir].dy;
将对象用作贴图
var directions = {
'left': {
dx : -1, dy : 0
},
'right': {
dx : 1, dy : 0
},
'up': {
dx : 0, dy : 1
},
'down': {
dx : 0, dy : -1
}
};
this.dx = directions[newDir].dx;
this.dy = directions[newDir].dy;
只是为了它
dir_map = {right:0,up:1,left:2,down:3}
dirs = [[1,0],[0,1],[-1,0],[0,-1]]
dir = dir_map[newDir] // and keep it as number from now on. Never get back to string.
this.dx += dirs[dir][0]
this.dy += dirs[dir][1]
即使需要空档方向:
if (dir != null) {
this.dx += dirs[dir][0]
this.dy += dirs[dir][1]
}
只是为了它
dir_map = {right:0,up:1,left:2,down:3}
dirs = [[1,0],[0,1],[-1,0],[0,-1]]
dir = dir_map[newDir] // and keep it as number from now on. Never get back to string.
this.dx += dirs[dir][0]
this.dy += dirs[dir][1]
即使需要空档方向:
if (dir != null) {
this.dx += dirs[dir][0]
this.dy += dirs[dir][1]
}
如果这段代码有效,你应该把它放在这个网站上。我投票决定关闭这个问题,因为它要求codereview。@FelixKling…这并不是堆栈溢出的明确主题。请阅读@Simon:这个链接似乎证实了这个问题非常适合CodeReview(尽管我实际上没有建议将它移到那里)。另请参见。@FelixKling:仅仅因为它是一个很好的配合,并不能使它偏离主题。问题可以适用于多个站点。如果此代码有效,您应该将其放在此站点上。我投票决定将此问题作为主题外的问题关闭,因为它要求codereview。@FelixKling…这并不是堆栈溢出的明确主题外的问题。请阅读@Simon:这个链接似乎证实了这个问题非常适合CodeReview(尽管我实际上没有建议将它移到那里)。另请参见。@FelixKling:仅仅因为它是一个很好的配合,并不能使它偏离主题。问题可以适用于多个站点。