【问题标题】:I can't output elements within my array when I use a for loop使用 for 循环时无法输出数组中的元素
【发布时间】:2025-11-28 14:15:01
【问题描述】:

我创建了一个函数,它根据条目的数量向我的 html 表中添加行。

我正在尝试使用 id 变量将变量 cdNoCell 设为唯一 ID,该 ID 会随着生成的每一行而递增。

我遇到的问题是 id 打印出表格中每一行的元素总数。所以如果我有 4 个元素,它会打印出来:

实际输出:

ID    Title    Cost
4     a        10
4     b        12
4     c        6
4     d        10

预期输出:

ID    Title    Cost
1     a        10
2     b        12
3     c        6
4     d        10

我的功能码:

function showFunction(){
    var costArrayLength = costArray.length;
    for (i = 0; i<costArrayLength; i++){ //for loop adding elements to table
        var table = document.getElementById("myTable"); 
        var row = table.insertRow(-1); //adds each element to the bottom of table
        var cdNoCell = row.insertCell(0);
        var cdTitleCell = row.insertCell(1);
        var cdCostCell = row.insertCell(2); //inserts 3 cells 
        var id = 1;
        cdNoCell.innerHTML = id;
        cdCostCell.innerHTML = costArray[i];
        cdTitleCell.innerHTML = titleArray[i];
        id++;
    }
}

【问题讨论】:

  • 只需将var id = 1; 放在循环之前。

标签: javascript html increment


【解决方案1】:

你应该可以改变这一行

cdNoCell.innerHTML = id;

有了这个

cdNoCell.innerHTML = i + 1;

然后,您可以从代码中同时删除 var id = 1;id++;

【讨论】:

    【解决方案2】:

    由于您的循环中有var id = 1;,因此循环将重新启动并每次输出 1,而不是按预期增加。

    我有点猜测你的数组,但在下面你可以看到一个工作的 sn-p。还要记住,插入函数足够聪明,可以知道下一个单元格或行。

    titleArray = new Array("a","b", "c");
    costArray = new Array(10, 20, 30);
    
    function showFunction(){
        var costArrayLength = costArray.length;
        var id = 1;
        
        for (i = 0; i<costArrayLength; i++){ //for loop adding elements to table
            var table = document.getElementById("myTable"); 
            var row = table.insertRow(); //adds each element to the bottom of table
            var cdNoCell = row.insertCell();
            var cdTitleCell = row.insertCell();
            var cdCostCell = row.insertCell(); //inserts 3 cells 
            cdNoCell.innerHTML = id;
            cdCostCell.innerHTML = costArray[i];
            cdTitleCell.innerHTML = titleArray[i];
            id++;
        }
    }
    
    showFunction();
    <table id="myTable" border=1>
    
    </table>

    【讨论】: