0
var dril1 = (count1[0]*m[1])+(count1[1]*m[2])+(count1[2]*m[3])+(count1[3]*m[4])+(count1[4]*m[5])+(count1[5]*m[6]);
var dril2 = (count2[0]*m[1])+(count2[1]*m[2])+(count2[2]*m[3])+(count2[3]*m[4])+(count2[4]*m[5])+(count2[5]*m[6]);
var dril3 = (count3[0]*m[1])+(count3[1]*m[2])+(count3[2]*m[3])+(count3[3]*m[4])+(count3[4]*m[5])+(count3[5]*m[6]);
var dril4 = (count4[0]*m[1])+(count4[1]*m[2])+(count4[2]*m[3])+(count4[3]*m[4])+(count4[4]*m[5])+(count4[5]*m[6]);
var dril5 = (count5[0]*m[1])+(count5[1]*m[2])+(count5[2]*m[3])+(count5[3]*m[4])+(count5[4]*m[5])+(count5[5]*m[6]);
var dril6 = (count6[0]*m[1])+(count6[1]*m[2])+(count6[2]*m[3])+(count6[3]*m[4])+(count6[4]*m[5])+(count6[5]*m[6]);

还有其他可能的方法来编写这段代码吗?

4

6 回答 6

2

这个:

var counts = [ count1, count2, count3, count4, count5, count6 ];

接着:

var drils = counts.map(function ( count ) {
    return count.reduce(function ( prev, curr, i ) {
        return prev + curr * m[ i + 1 ];
    }, 0 );
});

.map()Array 方法将根据数组返回一个新的结果数组counts.reduce()Array 方法会将每个元素缩减count为单个值。

于 2012-10-04T16:27:15.980 回答
0

对于每个练习,您可以执行以下操作:

var dril1 = (count1[0]*m[1])+(count1[1]*m[2])+(count1[2]*m[3])+(count1[3]*m[4]) +(count1[4]*m[5])+(count1[5]*m[6]);

var dril1 = 0;
var dril2 = 0;
for (var i=0, len=count1.length; i<len; i++) {
  dril1 += (count1[i]*m[i+1]);
  dril2 += (count2[i]*m[i+1]);
}

但是,如果您将每个计数都视为数组的成员:

var dril = [];
for (var i=0, lenI=count.length; i<lenI; i++) {
  dril[i] = 0;
  for (var j=0, lenJ=count[i].length; j<lenJ; j++) {
    dril[i] += (count[i][j]*m[j+1]);
  }
}
于 2012-10-04T16:24:56.183 回答
0

count[1...6]并且drill[1...6]实际上应该是它自己的数组。然后,您可以遍历元素并以这种方式进行调用。

var drill = []
for(var i = 0; i < count.length; i++){
    drill.push((count[i][0]*m[1]/* rest of the statement */));
于 2012-10-04T16:21:40.947 回答
0

看起来您可以使用二维数组,然后使用双循环?

于 2012-10-04T16:22:28.320 回答
0

至少,您可以循环求和:

var dril1 = 0, dril2 = 2, ...;
for (i = 0; i < 5; ++i) {
    dril1 += count1[i] * m[i + 1];
    dril2 += count2[i] * m[i + 1];
    . . .
}

dril1如果, ...,dril6count1, ...count6是两个数组,它可以被进一步压缩。

于 2012-10-04T16:23:51.143 回答
0

您可以重构计算:

function calc(count) {
  return count[0] * m[1] + count[1] * m[2] + count[2] * m[3] + count[3] * m[4] + count[4] * m[5] + count[5] * m[6];
}

var dril1 = calc(count1);
var dril2 = calc(count2);
var dril3 = calc(count3);
var dril4 = calc(count4);
var dril5 = calc(count5);
var dril6 = calc(count6);
于 2012-10-04T16:24:14.577 回答