Using an array instead of a chain of if / else blocks or a giant switch statement will be faster, more flexible, and less error prone. In addition, you do not have to worry if dir is a number or a string. Instead:
if(dir==0){img+='N.png';} else if(dir==1){img+='NE.png';} else if(dir==2){img+='E.png';} else if(dir==3){img+='SE.png';} else if(dir==4){img+='S.png';} else if(dir==5){img+='SO.png';} else if(dir==6){img+='O.png';} else if(dir==7){img+='NO.png';}
you can save the file names in an array:
var images = [ 'N.png', 'NE.png', 'E.png', 'SE.png', 'S.png', 'SO.png', 'O.png', 'NO.png' ];
or perhaps more readable:
var images = "N.png NE.png E.png SE.png S.png SO.png O.png NO.png".split(' ');
and then use only:
img = images[dir];
A full implementation of getDirections using an array will be:
var images = "N.png NE.png E.png SE.png S.png SO.png O.png NO.png".split(' '); function getDirections(dir) { var img = images[dir]; if (!img) { alert("something"); } return img; }
Does it work for you?
If images used only in this function, you might want to save it as a property of the function to avoid polluting your namespace as follows:
function getDirections(dir) { var img = getDirections.images[dir]; if (!img) { alert("something"); } return img; } getDirections.images = "N.png NE.png E.png SE.png S.png SO.png O.png NO.png".split(' ');
or use closure.
rsp
source share