【问题标题】:How to preserve the leading zero when changing a string into a number using Javascript?使用Javascript将字符串更改为数字时如何保留前导零?
【发布时间】:2021-03-20 22:14:17
【问题描述】:

如何将"03" 等字符串转换为数字并在字符串开头保留零?使用Number("03") 将删除前导0 并返回3,但我想将0 保留在那里。我该怎么做呢?

这是我的上下文 JS 函数:

function format(input, unit) {
  if (new RegExp(unit, 'i').test('minute second')) {
    if (String(input).length === 1) return Number(`0${input}`);
    else return input;
  }
  else if (unit === 'hour') {
    return input;
  }
}

谢谢!

编辑:到目前为止我得到了什么

let timer = {
  hours: 0,
  minutes: 1,
  seconds: 30,
  updateTimerDisplay() {
    document.getElementById('hour').innerHTML = this.hour;
    document.getElementById('minute').innerHTML = String(format(this.minutes, 'minute'));
    document.getElementById('second').innerHTML = String(format(this.seconds, 'second'));
  },
  startTimer() {
    const { updateTimerDisplay: updateDisplay } = this;
    let update = setInterval(_ => {
      this.seconds -= 1;
      if (this.seconds < 0) {
        this.seconds = 59;
        this.minutes -= 1;
      }
      if (this.minutes < 0) {
        this.minutes = 59;
        this.hours -= 1;
      }
      updateDisplay();
    }, 1000);
  }
};
timer.updateTimerDisplay();
timer.startTimer();

function format(input, unit) {
  if (new RegExp(unit, 'i').test('minute second')) {
    if (String(input).length === 1) return `0${input}`;
    else return String(input);
  }
}

【问题讨论】:

  • JavaScript 数字没有前导零?请问您需要前导零的原因是什么?
  • 数字是数字,而不是字符串。要查看前导零,甚至是其十进制表示,始终是将其转回字符串的过程。
  • @evolutionxbox 这是一个计时器,我希望能够像时钟一样在分钟和秒的开头添加零。
  • 在这种情况下,您说的是字符串,而不是数字。
  • 能否提供minimal reproducible example 说明您希望如何使用它?也许你到目前为止做了什么?

标签: javascript type-conversion


【解决方案1】:

一些问题:

  • this.hour: 的拼写应该是this.hours
  • 通过调用updateDisplay,您不会传递this 的预期值。最好保留方法的原始名称,并使用this.updateTimerDisplay
  • 不要将前缀为 0 的字符串转换回数字:您对要显示的内容感兴趣,因此请保持字符串格式。

无需过多更改代码中的其他内容,以上更正即可使其正常工作:

let timer = {
  hours: 0,
  minutes: 1,
  seconds: 30,
  updateTimerDisplay() {
    // Use textContent, not innerHTML (that is for HTML content)
    document.getElementById('hour').textContent = this.hours; // spelling!
    // The function format returns a string, so no need to call String on it:
    document.getElementById('minute').textContent = format(this.minutes, 'minute');
    document.getElementById('second').textContent = format(this.seconds, 'second');
  },
  startTimer() {
    // Don't read a function reference into a variable, as you'll lose the this-binding
    // --------- const { updateTimerDisplay: updateDisplay } = this;
    let update = setInterval(_ => {
      this.seconds -= 1;
      if (this.seconds < 0) {
        this.seconds = 59;
        this.minutes -= 1;
      }
      if (this.minutes < 0) {
        this.minutes = 59;
        this.hours -= 1;
      }
      // By having `this.` here, you pass that this-reference to the function
      this.updateTimerDisplay();
    }, 1000);
  }
};
timer.updateTimerDisplay();
timer.startTimer();

function format(input, unit) {
  // RegExp is overkill here. Just use includes:
  if (['minute', 'second'].includes(unit.toLowerCase())) {
    // Don't convert with Number: it must be a string:
    if (String(input).length === 1) return `0${input}`;
    else return String(input);
  }
}
&lt;span id="hour"&gt;&lt;/span&gt;:&lt;span id="minute"&gt;&lt;/span&gt;:&lt;span id="second"&gt;&lt;/span&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 2021-12-16
    • 2022-01-03
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多