-1

我有以下一段代码

var total = 5;
var arr = new Array("750", "400", "432", "355", "263");
id = 0;
num = 100;
var ht = 310;
var max = 750;
var cm = 20;
var bHg = 0;
var wdt = 100;
var bm = 20;
for (var i = 0; i < total; i++) {
    ar = parseInt(arr[i]);
    // how to rewrite these equations
    **bHg = (ar * ht / max) / num * id;
    printfu(cm + 50 + (i * (wdt + bm)) + bm,
                cm + (ht - bHg), wdt, bHg);**
}

function printfu(a,b,c,d) {
    document.write(a + b + c + d + "\n");
}

从学习的目的来看,我怎样才能用不同的方程写两行来产生相同的输出

bHg = (ar * ht / max) / num * id;
printfu(cm + 50 + (i * (wdt + bm)) + bm, cm + (ht - bHg), wdt, bHg);

以上的输出

520 640 760 880 1000

4

2 回答 2

1

这两行可以简化为:i * k1 + k2wherek1k2are constants。

完整的解决方案:

var total = 5;
var arr = new Array("750", "400", "432", "355", "263");
id = 0;
num = 100;
var ht = 310;
var max = 750;
var cm = 20;
var bHg = 0;
var wdt = 100;
var bm = 20;

/*
// It helps to note the bHG is ar times some constant.

var k = ht / max * num * id
var kA = (i * (wdt + bm)) + bm + cm + 50;
var kB = cm + (ht - bHg);
var kC = wdt;
var kD = bHg;

// bHg = ar * k;
var sum = kA + kB + kC + kD;
//=> (i * (wdt + bm)) + bm + cm + 50 + cm + (ht - bHg) + wdt + bHg
//=> (i * (wdt + bm)) + bm + 2*cm + 50 + ht + wdt
*/

var k1 = wdt + bm;
var k2 = bm + 2*cm + 50 + ht + wdt;

for (var i = 0; i < total; i++) {
   document.write(i * k1 + k2 + "\n");
}

//function printfu(a,b,c,d) {
//    document.write(a + b + c + d + "\n");
//}
于 2012-05-28T01:32:59.383 回答
0

好吧,从外观上看,我想您可以预先计算一些东西。如果我没记错的话,该printfu函数将数字加在一起?在这种情况下,它简化为:

cm + 50 + i * (wdt + bm) + bm + cm + ht - bHg + wdt + bHg
= 2*cm + i*(wdt + bm) + bm + ht + wdt + 50

由于它不再依赖于 bHg,因此您也可以预先计算它。所以这会起作用:

var pcp = ht * id / max / num,
    pcq = 2*cm + bm + ht + wdt + 50;
for( var i=0;...) {
    bHg = ar * pcp;
    document.write((pcq + i*(wdt+bm))+"\n");
}
于 2012-05-28T01:32:26.930 回答