简体   繁体   中英

Javascript showing number with leading zero

I am new to javascript, while i was trying to test an example with below code, Code:

 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> 

i am sending parameter as 'abc' and 010. But in output I am getting like below,

Output: abc is 8 years old

When JavaScript encounters a number preceeded by a 0, it assumes an octal is being used, hence the 8. As Eddie stated in the comments, the best way to avoid this would be by converting the number to a string by encasing it in quotations. Hope this example below helps!

Try

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

and use + sign to convert the string to the number explicitly.

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

When you do 010 , it gets treated as base 8 which is octal. The decimal representation of octal 010 is 8 . That is the reason you seeing 8 .

Either remove that zero or pass it as a string like below

 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> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM