gpt4 book ai didi

javascript - 在 Javascript 中创建表格

转载 作者:行者123 更新时间:2023-11-30 05:32:23 25 4
gpt4 key购买 nike

我有一个问题。我正在学习 javascript,但我不知道如何创建仅适用于 javascript 文件的表。我必须为每个字母频率输出创建一个表,但我不知道该怎么做。这是我应该拥有的输出:

output of the exercise

一开始我想在 HTML 上工作,但我不能,因为那部分与测试相关,我的代码必须通过。在这里我将展示其中的一些:

display_letter_frequency(letter_frequency("Hello"),document.getElementById("frequency_table"));
var rows = document.getElementById("frequency_table").querySelectorAll('tr')
equal(rows.length, 4, "With input String 'Hello' there should be 4 table rows")
equal(rows[0].querySelectorAll('td')[0].innerHTML, 'H', "1st td of 1st tr should have the value H");
equal(rows[0].querySelectorAll('td')[1].innerHTML, '1', "2nd td of 1st tr should have the value 1");
equal(rows[1].querySelectorAll('td')[0].innerHTML, 'E', "1st td of 2nd tr should have the value E");
equal(rows[1].querySelectorAll('td')[1].innerHTML, '1', "2nd td of 2nd tr should have the value 1");
equal(rows[2].querySelectorAll('td')[0].innerHTML, 'L', "1st td of 3rd tr should have the value L");
equal(rows[2].querySelectorAll('td')[1].innerHTML, '2', "2nd td of 3rd tr should have the value 2");
equal(rows[3].querySelectorAll('td')[0].innerHTML, 'O', "1st td of 4th tr should have the value O");
equal(rows[3].querySelectorAll('td')[1].innerHTML, '1', "2nd td of 4th tr should have the value 1");

此外,我不能使用 console.log,只能编写将由测试人员回调的函数代码。这是我所做的,但我不知道它是否正确以及如何继续:

function display_letter_frequency(a,dom) {
if(a === undefined){
return undefined
} else {
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for(var x in a){
var row = document.createElement("tr");

}
}
}

此代码与我之前编写的函数有关,该函数在命令行中计算用户的频率字母:

function letter_frequency(s) {
if(s === undefined){
return undefined
} else {
var freq = {};
for (var i = 0; i < s.length; i++) {
var character = s.charAt(i).toUpperCase();
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
}
return freq;
}

希望问题很清楚,你可以帮助我和需要它的人。我环顾了网络,他们讨论了一些频率表来定义我的问题。不知道对不对

最佳答案

尝试

for(var x in a){
var row = document.createElement("tr");
letterCell = document.createElement('td');
freqCell = document.createElement('td');
letterCell.innerHTML = x;
freqCell.innerHTML = a[x];
row.appendChild(letterCell);
row.appendChild(freqCell);
tblBody.appendChild(row);
}
}

(未测试)

关于javascript - 在 Javascript 中创建表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26056107/

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