javascript - 为什么这个长度函数未定义?

标签 javascript jquery html css

<分区>

我想得到秒的长度。如果秒是一个字符而不是加 0 否则什么都不做。 这是我的代码

    <p>Click the button to display the seconds of the time right now.</p>
    <p id="demo"></p>
    <script>
      var d = new Date();
      var n = d.getSeconds();
      var z = n.length;
      document.getElementById("demo").innerHTML = z;
    </script>

最佳答案

getSeconds 函数返回一个没有长度属性的数字。

如果您想获取数字中有多少个字符,您可以使用 .toString() 将其转换为字符串

 <p>Click the button to display the seconds of the time right now.</p>
    <p id="demo"></p>
    <script>
      var d = new Date();
      var n = d.getSeconds();
      var z = n.toString().length;
      document.getElementById("demo").innerHTML = z;
    </script>

关于javascript - 为什么这个长度函数未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58748933/

上一篇:html - 图像上的响应式 div

下一篇:html - float 无法覆盖我的整个背景。这是为什么?

相关文章:

jQuery slideDown/slideUp 问题

javascript - 三.JS:获取旋转物体的位置

javascript - 从 api 调用中检索 ng-options 的值

javascript - 如何在俄罗斯方 block 游戏中正确使用requestAnimationFrame函数?

jquery - 将表格中的第 th 个元素垂直居中

javascript - 加载 svg 文件(xml)并使用 javascript 提取特定信息

javascript - 帧中的动画持续时间是什么意思?

javascript - Vanilla JS 事件委托(delegate)(不是点击事件)返回的不仅仅是文档对象

html - 响应式 iframe 中的三个 div

javascript - jQuery/Bootstrap 跟随带有悬停项的 div