JS:如何嵌套for循环而不使第一个循环循环?

时间:2014-07-02 12:22:07

标签: javascript loops

我的for循环设置问题:

var gain = prompt("Please enter the GAIN value");
var rtp = prompt("Please enter the RTP value");
var equation = function (gaininput, mdecinput) {
    rs = 2.56 * mdecinput / (0.0002 * gaininput * Math.pow(2, 24));
    return rs;
};

var sum = 0;
var co = [439.932854, 472.41802, 37.684494, 7.472018, 2.920828, 0.005184, -0.963864, -0.188732, 0.191203, 0.049025];
var cohigh = [0.183324722, 0.240975303, 0.209108771, 0.190439972, 0.142648498, 0.077993465, 0.012475611, -0.032267127, -0.075291522, -0.05647067, 0.076201285, 0.123893204, -0.029201193, -0.091173542, 0.001317696, 0.026025526];

for (var i = 0; i <= 16777215; i += 5000) {
    var rsoutput = equation(gain, i);
    var w = (rsoutput / rtp);
    document.writeln((i) + '. ' + rsoutput + '<br/>');
    var blackbox = function blackbox(b) {
        var coefficient = co[b];
            if (w<1){
                coefficient = co[b];
                }
            else{
                coefficient = cohigh[b];
                }
    return (coefficient * Math.pow(((Math.pow(w, 1 / 6) - 0.65) / 0.35, b), b));
    };
    if (w<1){
        for (var j = 0; j <= 15; j++) {
            sum = sum + blackbox(j);
            sum = sum * 273.16;
            document.writeln("YOUR SUM: " + sum + '<br/>');
        }
    }   
    else {
        for (var jtwo = 0; jtwo<=15; j++) {
            sum = sum + blackbox(j);
            sum = sum * 273.16;
            document.writeln("YOUR SUM: " + sum + '<br/>');
        }
    }
}  

var temp = prompt("Enter the temperature in KELVIN");
console.log("YOUR TEMPERATURE: " + temp * 1.86455556 + '<br/>');

当我运行此代码时,会发生的事情是第一个循环将if / else语句循环1600万次。我不希望这种情况发生,但我必须将if / else语句放在此循环中,以便我可以调用变量w。有解决方法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

好吧,如果你不想在循环中运行if语句,那么我会将它们移出,如果唯一的问题是从循环外部访问W变量然后移动“var w;”的延迟在循环之外(上方)。然后if语句也可以访问它。

var w;
for (var i = 0; i <= 16777215; i += 5000)
{
    w = (rsoutput / rtp);
    **do stuff**
}
if (w<1)
{
}
else
{}