循环时输出额外+; JavaScript的

时间:2015-03-30 16:38:24

标签: javascript loops

我想要的输出是:5 + 6 + 7 + 8 + 9 + 10 = 45

我得到的输出是:1 + 2 + 3 + 4 + 5 + = 15(末尾有额外的+侧)。我不确定如何在没有额外+的情况下将其输出,并且我显然没有找到合适的术语来解决它。谢谢!

这是我的代码: function exercise7Part2(){     //第2部分:您的代码在此行之后开始

// Declare variables
var loopStart;
var loopMax;
var total;

// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:")); 

total = 0;

// Processing
while (loopStart <= loopMax)
{
    total += loopStart;
    document.write(loopStart + " + ");
    loopStart++;   
}
document.write(" = " + total);

}

2 个答案:

答案 0 :(得分:1)

这是因为您正在打印loopState + "+",这将始终在最后打印+。相反,您必须检查它是否为最后一个值并阻止+打印,否则,请使用三元运算符进行打印。

在这个例子中,我检查loopStart和loopMax是否不相等。如果他们不相等,那么最后会追加+

就像:

    document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));

此处(loopStart!=loopMax ? "+" : "")是三元运算符。 loopStart!=loopMax是一个布尔表达式。它已被评估,如果它是真的,?之后的第一个参数将被使用,所以在这种情况下+如果它{false},那么:之后将使用它在这种情况下,它是""空字符串。

&#13;
&#13;
// Declare variables
var loopStart;
var loopMax;
var total;

// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:")); 

total = 0;

// Processing
while (loopStart <= loopMax)
{
    total += loopStart;
    document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
    loopStart++;   
}
document.write(" = " + total);
&#13;
&#13;
&#13;

使用正常if条件块

while (loopStart <= loopMax)
{
    total += loopStart;
    if(loopStart===loopMax) {
       document.write(loopStart);
    } else {
       document.write(loopStart+ "+");
    }
    loopStart++;   
}

答案 1 :(得分:0)

&#13;
&#13;
// Declare variables
var loopStart;
var loopMax;
var total;

// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:")); 

total = 0;

// Processing
while (loopStart <= loopMax)
{
    total += loopStart;
    document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
    loopStart++;   
}
document.write(" = " + total);
&#13;
&#13;
&#13;