I’ve been trying to add classes to elements in my page depending on which array they are, but I can’t find the problem in my code. I’m trying to find ‘.b001’ and add that element class ‘ct01’. The same for ‘.b005, .b002’ and add class ‘ct02’ and so on.
PadDigits adds the specified num of 0 before a number.
Thanks!!
function PadDigits(n, totalDigits) {
n = n.toString();
var pd = '';
if (totalDigits > n.length)
{
for (i=0; i < (totalDigits-n.length); i++)
{
pd += '0';
}
}
return pd + n.toString();
}
var filatrans = new Array();
filatrans[0] = '1';
filatrans[1] = '5 2';
filatrans[2] = '9 6 3';
filatrans[3] = '12 10 7 4';
filatrans[4] = '15 13 11';
filatrans[5] = '26 21 18 16 14';
filatrans[6] = '33 27 22 19 17';
filatrans[7] = '40 34 28 23 20';
filatrans[8] = '47 41 35 29 24';
filatrans[9] = '54 48 42 36 30 25';
filatrans[10] = '61 55 49 43 37 31';
filatrans[11] = '68 62 56 50 44 38 32';
filatrans[12] = '75 69 63 57 51 45 39';
filatrans[13] = '82 76 70 64 58 52 46';
filatrans[14] = '89 83 77 71 65 59 53';
filatrans[15] = '96 90 84 78 72 66 60';
filatrans[16] = '103 97 91 85 79 73 67';
filatrans[17] = '110 104 98 92 86 80 74';
filatrans[18] = '117 111 105 99 93 87 81';
filatrans[19] = '124 118 112 106 100 94 88';
filatrans[20] = '125 119 113 107 101 95';
filatrans[21] = '126 120 114 108 102';
filatrans[22] = '127 121 115 109';
filatrans[23] = '128 122 116';
filatrans[24] = '129 123';
filatrans[25] = '130';
var w = filatrans;
for (e=0; e<w.length; e++) {
fila = w[e].split(' ');
var out;
for (e=0; e<fila.length; e++) {
out += '.b' + PadDigits(fila[e], 3) + ', ';
}
$(out).addClass('ct' + PadDigits(e+1, 2));
}
The problem with the code is of course that you are using the same variable for the nested loops, as others already have mentioned.
Despite your title, you are not using multidimentional arrays, you are just using an array of strings, where you create a new array from each string on the fly. You can use the array literal syntax to simplify creation of the array, and also create it with actual arrays instead of strings. That way you don’t have to create the arrays in the loop.
I also made a simplified
padDigitsfunction.