【问题标题】:Javascript showing number with leading zeroJavascript 显示带有前导零的数字
【发布时间】:2017-12-04 06:41:28
【问题描述】:

我是 javascript 新手,当我尝试使用以下代码测试示例时, 代码:

function sayHello(name, age) {
  document.write (name + " is " + age + " years old.");
}
<p>Click the following button to call the function</p>  
<form>
   <input type="button" onclick="sayHello('abc', 010)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>

我将参数发送为“abc”和 010。但在输出中我得到如下所示,

输出: abc 8 岁了

【问题讨论】:

  • 您应该将010 作为字符串传递。或在连接之前将年龄转换为字符串

标签: javascript parameter-passing


【解决方案1】:

当 JavaScript 遇到一个以 0 开头的数字时,它假定正在使用八进制,因此是 8。正如 Eddie 在 cmets 中所说,避免这种情况的最佳方法是将数字转换为字符串,将其封装起来在引文中。希望下面的示例对您有所帮助!

试试

onclick="sayHello('abc', '010')"

并使用+号将字符串显式转换为数字。

console.log('age: ' , +age); //print age: 10

【讨论】:

    【解决方案2】:

    当您执行010 时,它会被视为基数8,即八进制。八进制 010 的十进制表示为 8。这就是你看到8的原因。

    要么删除该零,要么将其作为字符串传递,如下所示

    function sayHello(name, age) {
      document.write (name + " is " + age + " years old.");
    }
    <p>Click the following button to call the function</p>  
    <form>
       <input type="button" onclick="sayHello('abc', '010')" value="Say Hello">
    </form>
    <p>Use different parameters inside the function and then try...</p>

    【讨论】:

      【解决方案3】:

      Javacript 引擎将前导零解释为八进制数字文字。它在 EMCA Spec 的附录中定义 010 变成 8 * 1 = 8。

      【讨论】:

        猜你喜欢
        • 2010-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-11
        • 2022-01-10
        相关资源
        最近更新 更多