数组未在某些情况下填充

ini*_*tar 0 javascript

我很难解决这个问题,我很欣赏这个剧本.

尝试做倒计时脚本,我必须显示从前一个计数的新数字.

let oldN = 0;
let newN = 0;
let arr = [];

function runner() {
  arr = [];
  newN = document.getElementById('newVar').value;

  console.log("stored: " + oldN + " new: " + newN);

  if (oldN > newN) {
    for (let i = oldN; i >= newN; i--) {
      arr.push(i);
    }
  } else if (oldN < newN) {
    for (let e = oldN; e <= newN; e++) {
      arr.push(e);
    }
  }

  console.log("array: " + arr.length);
  oldN = newN;

  for (let u = 0; u < arr.length; u++) {
    (function(index) {
      setTimeout(() => {
        document.getElementsByTagName('span')[0].innerText = arr[index];
      }, 100 * u);
    })(u);
  }

}
Run Code Online (Sandbox Code Playgroud)
<div class="board">
  <span><!----></span>
</div>

<br/>
<input type="text" id="newVar" />
<button onclick="runner()">Start</button>
Run Code Online (Sandbox Code Playgroud)

它似乎工作,但如果我从13到7,它将不会填充阵列因此不运行倒计时,从7到13时会发生同样的问题.

任何的想法?

亲切的问候

Ber*_*rgi 5

您忘记将输入值(字符串)转换为数字.它们按字母顺序进行比较,而不是数字进行比较,"13" < "7"因此循环不起作用.使用

newN = parseInt(document.getElementById('newVar').value, 10);
Run Code Online (Sandbox Code Playgroud)

  • @ iniestar - 你有很多选择如何从字符串转换为数字; [我的回答](/sf/ask/2029638761/#28994875)描述了它们. (3认同)