我正在建立一个字数追踪器,并希望显示每天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>

08-19 16:52