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]);
还有其他可能的方法来编写这段代码吗?
答案 0 :(得分: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
元素减少为单个值。
答案 1 :(得分: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 */));
答案 2 :(得分:0)
看起来你可以使用2D数组,然后使用双循环?
答案 3 :(得分: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
,...,dril6
和count1
,...,count6
是两个数组,则可以进一步压缩。
答案 4 :(得分: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);
答案 5 :(得分: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]);
}
}