我正在构建一个字数统计跟踪器,并希望显示每天需要多少字数才能在 30 天内达到目标。例如,如果有人输入 50,000 作为目标,他们每天必须完成 1667 个单词。我想创建一个列表元素,其中包含:
Day 1: 1667
Day 2: 3334
Day 3....etc.
我当前的计划是创建一个包含列表元素的数组,但该脚本似乎导致网站完全崩溃!我不确定这里发生了什么。
let wordsPerDay = 0;
function wordsPerDayF(x) {
wordsPerDay = x / 30;
wordsPerDay = Math.round(wordsPerDay)
document.getElementById('wordsNeeded').innerHTML = wordsPerDay.toString();
};
// Above functions finds the word count needed per day
let milestones = []
let finalMilestones = [];
function createMilestones() {
let newWordCount = wordsPerDay;
for (let w = 1; w <= 30; w++) {
milestones.push(newWordCount)
newWordCount += newWordCount;
};
let count = 1;
for (let z = 0; z = milestones.length; z++) {
finalMilestones.push("Day " + count + ": " + milestones[z]);
count++;
};
};
function final() {
createMilestones();
let str = '<ul>'
finalMilestones.forEach(function(item) {
str += '<li>' + item + '</li>';
});
str += '</ul>';
document.getElementById("wordsNeeded").innerHTML = str;
};
final();
<div id="wordsNeeded"></div>
我是编码新手,所以如果这段代码很粗糙或难以理解,我深表歉意。
最佳答案
z = milestones.length
应该是z < milestones.length
.
你从来不打电话wordsPerDayF()
.
newWordCount += newWordCount
每天的字数都会增加一倍,但这并不是你真正想要的。您只需添加 newWordCount
至总计。您还可以使用w * newWordCount
获取每天的总数。
let wordsPerDay = 0;
function wordsPerDayF(x) {
wordsPerDay = x / 30;
wordsPerDay = Math.round(wordsPerDay)
document.getElementById('wordsNeeded').innerHTML = wordsPerDay.toString();
};
// Above functions finds the word count needed per day
let milestones = []
let finalMilestones = [];
function createMilestones() {
let newWordCount = wordsPerDay;
for (let w = 1; w <= 30; w++) {
milestones.push(newWordCount * w)
};
let count = 1;
for (let z = 0; z < milestones.length; z++) {
finalMilestones.push("Day " + count + ": " + milestones[z]);
count++;
};
};
function final() {
wordsPerDayF(50000);
createMilestones();
let str = '<ul>'
finalMilestones.forEach(function(item) {
str += '<li>' + item + '</li>';
});
str += '</ul>';
document.getElementById("wordsNeeded").innerHTML = str;
};
final();
<div id="wordsNeeded"></div>
关于Javascript:动态渲染列表[初学者],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58718333/