gpt4 book ai didi

javascript - 使用 for 循环时无法输出数组中的元素

转载 作者:太空宇宙 更新时间:2023-11-04 14:55:52 25 4
gpt4 key购买 nike

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

我正在尝试使变量 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++;
}
}

最佳答案

你应该可以改变这一行

cdNoCell.innerHTML = id;

有了这个

cdNoCell.innerHTML = i + 1;

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

关于javascript - 使用 for 循环时无法输出数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42657913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com