如何在JS中增加数组索引



我创建了一个JavaScript函数,在其中我定义了一个数组,并将数组值附加到HTML表中,但我不知道如何动态增加数组索引。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-striped">
<thead>
<tr>
<th id="time">Time Stamp</th>
<th id="tmpr">Temperature</th>
<th id="crrt">Current</th>
</tr>
</thead>
<tbody id="abc">
</tbody>
</table>
<script>
$(document).ready(function storetime() {
	var tim = [
		["11:34:4", 30, 31],
		["11:34:5", 34, 35],
		["11:34:6", 37, 39]
	];
	
	$.each(tim, function(i, val) {
		$("#abc").append(
			`<tr><td> (` + val[0] + `)</td> <td> (` + val[1] + `)</td></tr>`
		);
	});
});
</script>

一种可能的解决方案是创建一个表体元素字符串,并使用函数html在屏幕上呈现该字符串。

<script>
$(document).ready(function storetime() {
let html = '';
var tim = [['11:34:4', 30, 31], ['11:34:5', 34, 35], ['11:34:6', 37, 39]];
$.each(tim, function (i, val) {
html += `<tr><td> (${val[0]})</td> <td> (${val[1]})</td></tr>`;
});
$('#abc').html(html);
});
</script>

还有更多的解决方案,搜索createElement函数和appendChild函数。

最新更新