Javascript:动态渲染列表[初学者]

标签 javascript list function dom

我正在构建一个字数统计跟踪器,并希望显示每天需要多少字数才能在 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/

相关文章:

javascript - 使用 Webpack 从 SASS 导入 CSS-url

javascript - AngularJS - 用 $q promise 的函数在测试中没有解析

python - 预先列出 python

python - 如何在 Python 的包装函数中使用任意函数

javascript - 基于文档动态创建摘要

javascript - XMLHttpRequest 有时不发送字符串

python - 将 random.random() 结果转换为列表 - Python

list - 有没有办法用java 8流更改日期格式?

function - 在 Inno Setup 中实现脚本常量时为 "Identifier Expected"或 "Invalid Prototype"

php - `static` 函数内部的关键字?