我正在使用的二维数组的每一行都有不同的长度,例如:
var a = [2, 5, -12, 9];
var b = [54.0, 0.3];
var c = ["tree", "sun", "pool"]
var all = [a, b, c]
二维数组中的任何行有时都可能为零。上面的数组只是一个例子。
我想做的是从每个人的每一行中获取一个值,用这些值做一些事情,然后得到另一个值的组合,等等。
例子:
//IF ALL ROWS HAVE CONTENT
var values = [all[0][0], all[1][0], all[2][0]];
//do something with it
values = [all[0][0], all[1][0], all[2][1]];
//do something with it
......
values = [all[0][3], all[1][1], all[2][2]];
//do something with it
//IF FIRST AND THRID ROWS HAVE CONTENT, THE SAMPLE OUTPUT
var values = [all[0][0], all[2][0]];
values = [all[0][0], all[2][1]];
......
values = [all[0][3], all[2][2]];
//IF ONLY SECOND ROWS HAVE CONTENT, THE SAMPLE OUTPUT
var values = [all[1][0]];
values = [all[1][1]];
这是我对代码逻辑流程的想法
//count how many rows are not empty
var arrayCount = 0;
for(var i=0; i < all.length; i++){
if(all[i].length !== 0){
arrayCount++;
}
}
//store the combination of values each time
var values = [];
//reference for rows
var x; var y;
//differentiate the looping based on the number of unempty rows
switch(arrayCount){
//one unempty row
case 1:
//figure out which one is not empty and set a's pointer to it
for(var q = 0; q < x.length; q++){
values.push(x[q]);
//do something with it
values.splice(1, 0);
}
break;
case 2:
//figure out which one are not empty and set a and b's pointer to them (don't know how, maybe using two loops for each row?)
for(var q = 0; q < x.length; q++){
values.push(x[q]);
for(var p = 0; p < y.length; p++){
values.push(y[p]);
//do something with it
values.splice(1, 1);
}
values.splice(1, 0);
}
break;
case 3:
//set pointers to all the rows
for(var q = 0; q < x.length; q++){
values.push(x[q]);
for(var p = 0; p < y.length; p++){
values.push(y[p]);
for(var r = 0; r < z.length; r++){
values.push(z[r]);
//do something with it
values.splice(1, 2);
}
values.splice(1, 1);
}
values.splice(1, 0);
}
break;
}
恐怕整个代码太长了,并且在开关中有一些重复的代码。可以简化吗?
我确实看到了同样问题的帖子,我尝试了它的答案。不幸的是,我正在编码的平台(Fandom)不支持这个生成器功能。我问,它只支持 Javascript 到 ES3 或 ES4。
谢谢你看这个问题!