for循环。无法对声明

时间:2017-05-03 02:08:10

标签: javascript

function forfunction() {
    var arrNums = [4,15,10,7,6,23,1,18,8,45,-5,16,9,68];
    var output = "";
    output = "FOR RESULTS: ";
    var index = 0;
    for (index = 13; index < arrNums.length && index >= 0; index--) {
     output = output + arrNums[index] + " ";        
    }
    document.getElementById("msg2").innerHTML = output;
}

我被告知我不允许对声明进行硬编码,如何更改&#39; for&#39;声明,所以我不是硬编码?

1 个答案:

答案 0 :(得分:0)

您的循环逻辑不正确:

如果要按顺序打印数字,请在下面使用:

function forfunction() {
    var arrNums = [4,15,10,7,6,23,1,18,8,45,-5,16,9,68];
    var output = "";
    output = "FOR RESULTS: ";
    var index = 0;
    for (; index < arrNums.length; index++) {
     output = output + arrNums[index] + " ";        
    }
    document.getElementById("container").innerHTML = output;
}

如果要以相反的顺序打印,请在下面使用:

function forfunction() {
    var arrNums = [4,15,10,7,6,23,1,18,8,45,-5,16,9,68];
    var output = "";
    output = "FOR RESULTS: ";
    var index = arrNums.length-1;
    for (; index >=0; index--) {
     output = output + arrNums[index] + " ";        
    }
    document.getElementById("container").innerHTML = output;
}