在写一个巨大的if语句时有没有办法节省空间?

时间:2016-09-01 15:55:09

标签: javascript jquery

假设我有两个变量, x z ,它代表坐标。 在我的JavaScript代码中,我想要为x / z(最多一千)的组合发生特定的事情。 由于代码很长,我想知道是否有任何方法可以缩短这种代码:

if (x == 12 && z == 14) {
  doThis(23);
  alert("doo");
  doThat(661);
}
if (x == 13 && z == 14) {
  doThis(2345);
  alert("dee");
  doThat(166);
}
if (x == 13 && z == 15) {
  doThis(12);
  alert("duu");
  doThat(44);
}

......等等。我知道要使文件变小和放大更紧凑我可以移除所有空间并使所有空间都在一行 - 但我如何使它更短?

编辑: doThis()和doThat()只是其中“代码”的示例。在所有if语句中,代码实际上完全不同。现在改了。

2 个答案:

答案 0 :(得分:0)

构建一个json对象,以便:

“12”中有“13”和“14”,

“13”中有“11”,“12”和“13”,

所以你首先检查zson对象中是否存在z,然后如果j存在于json对象中的z对象中。

zxMap.hasOwnProperty('12')

then if true, get that to another object variable(or an array) and check

foundZ.hasOwnProperty('13')

or

foundZ.includes("13");

然后这应该给出真或假

因此,一旦构建了json对象,只需要2“if”。

{
  "12": ["13","14"],
  "13": ["11","12","13"]
}

然后编写两个函数来检查z和x值:

if(has_x(has_z("12"),"13"))
{
   do_this();do_that();
}

如果do_this有差异,

{
  "12": {"13":"doo","14":"dee"},
  "13": {"11":"daa","12":"duu","13":"dii"}]
}

if(has_x(has_z("12"),"13"))
{
   do_this();
   alert(extract_message("12","13"));
   do_that(); 
}

它甚至可以是json对象中最后一个元素中的代码字符串,以javascript的形式执行。

  eval(extract_message("12","13"));

答案 1 :(得分:0)

If the values of x and z determine completely different code as you have suggested, then something like this might simplify things.

var work = (function(){
    var _work = {};
    var _getKey = function(x, z){ return x + "~" + z;};
    var _set = function(x, z, fn) { _work[_getKey(x,z)] = fn; }
    var _get = function(x, z) { return _work[_getKey(x,z)] ;}
    return {get : _get, set : _set};
})();

work.set(12, 14, function(){
  // code unique to this combination of x and z
  console.log("doo");
});

work.set(13, 14, function(){
  // code unique to this combination of x and z
  console.log("dee");
});

work.set(13, 15, function(){
  // code unique to this combination of x and z
  console.log("duu");
});

var x = 12;
var z = 14;
work.get(x, z)();

On the other hand, if the code is the same, except for parameter values (per your code example), then something like this (as suggested by @Teemu and @hindmost) would be superior

function doThis(param){}
function doThat(param){}

var work = (function(){
    var _work = {};
    var _getKey = function(x, z){ return x + "~" + z;};
    var _set = function(x, z, args) { _work[_getKey(x,z)] = args; }
    var _get = function(x, z) { return _work[_getKey(x,z)] ;}
    return {get : _get, set : _set};
})();

work.set(12, 14, [23, "doo", 666]);
work.set(13, 14, [2345, "dee", 166]);
work.set(13, 15, [12, "duu", 44]);

var x = 12;
var z = 14;
var args = work.get(x, z);

doThis(args[0]);
console.log(args[1]);
doThat(args[2]);  

Given that x and z have now been identified as coordinates, the note in your original post from @OregonTrail is probably the right direction.