JS程序输出奇数

时间:2014-03-04 15:30:54

标签: javascript loops output

我目前正在尝试让我的程序正常运行。它应该将数字从低到高的因子分解。换句话说,如果下限为12,并且上限为16,则应将以下内容输出到标记....

12: 2,3,4,6,12
13: 13
14: 2,7,14
15: 3,5,15
etc.....

但是,我得到的结果如下:

12: 2,3,4,6,12,
13,
2,7,14,
3,5,15,
2,4,8,16,
17,

它以奇怪的方式输出,我一直试图移动它。唯一正确的是前一行。这里有人可以帮我一把吗?我确信这是次要的,但我无法得到它......

    function calculate(num){
    var int = 2;    
    var num = document.getElementById("num").value;
    var high = document.getElementById("high").value;
    var str = num + ": ";


    while (num <= high){

    for (var i = 2; i <= num; i++){
        if(num % i == 0){
            str += i + ",";         
        }

    }   
    num++;

    str += "\n";
    }
    document.getElementById("outputArea").innerHTML = str;
}

3 个答案:

答案 0 :(得分:0)

您只需添加num + ': '一次。将其更改为:

function calculate(num) {
    var int = 2;
    var num = document.getElementById("num").value;
    var high = document.getElementById("high").value;
    //var str = num + ": "; // this doesn't go here.

    while (num <= high) {
        var str = num + ": "; // this goes here
        for (var i = 2; i <= num; i++) {
            if (num % i == 0) {
                str += i + ",";
            }

        }
        num++;

        str += "\n";
    }
    document.getElementById("outputArea").innerHTML = str;
}

答案 1 :(得分:0)

您的num + ': '位置不正确。此外,您将始终打印一个逗号,除非有多个逗号,否则您不应该这样做。 \n无效,因为您使用HTML显示它,因此我将其更改为<br>

这是我更新的功能:

function calculate() {
    var int = 2;
    var num = document.getElementById("num").value;
    var high = document.getElementById("high").value;
    var str = "";


    while (num <= high) {
        str += num + ": ";
        var first = true;
        for (var i = 2; i <= num; i++) {
            if (num % i == 0) {
                str += ((!first) ? ", " : "") + i;
                first = false;
            }
        }
        num++;
        str += "<br>";
    }

    document.getElementById("outputArea").innerHTML = str;
}

JSFiddle:http://jsfiddle.net/howderek/Bfeva/

答案 2 :(得分:0)

你必须在循环中定义 str ,然后执行:

  str += num + ": ";
在里面。就像在这个DEMO.

中一样
var str = "";
while (num <= high) {
    str += num + ": ";
    for (var i = 2; i <= num; i++) { 
        if (num % i === 0) {               
            str += i + ",";
        }
    }
    num++;
    str += "\n";
}

如果你不想要最后一个逗号,你必须在for循环中添加这个检查:

str += i;
if (i != num) {
  str += ",";
}