问题描述
我将id作为参数传递给javascript函数,因为它来自UI,它是零填充的。但它似乎有(可能)奇怪的行为?
I'm passing as parameter an id to a javascript function, because it comes from UI, it's left zero padded. but it seems to have (maybe) "strange" behaviour?
console.log(0000020948); //20948
console.log(0000022115); //9293 which is 22115's octal
console.log(parseInt(0000022115, 10)); // 9293 which is 22115's octal
console.log(0000033959); //33959
console.log(20948); //20948
console.log(22115); //22115
console.log(33959); //33959
我怎样才能确保它们正确解析到它们是什么? (十进制)
how can I make sure they are parsing to right numebr they are? (decimal)
编辑:
更清楚:
这些数字来自服务器并且是零填充字符串。我正在为每个按钮创建一个删除按钮。
those numbers come from the server and are zero padded strings. and I'm making a delete button for each one.
喜欢:
function printDelButton(value){
console.log(typeof value); //output string
return '<a href="#" onclick="deleteme('+value+')"><img src="images/del.png"></a>'
}
and
function printDelButton(value){
console.log(typeof value); //output numeric
console.log(value); //here output as octal .... :S
}
我试过: console.log(parseInt(0000022115,10)); // 9293这是22115的八进制
并且仍在解析为八进制
I tried :console.log(parseInt(0000022115, 10)); // 9293 which is 22115's octal
and still parsing as Octal
推荐答案
如果您收到的参数为字符串对象,应该可以使用
If you receive your parameters as string objects, it should work to use
parseInt(string, 10)
将字符串解释为十进制,即使它们以0开头。
to interpret strings as decimal, even if they are beginning with 0.
在测试中,你传递parseInt方法一个数字,而不是一个字符串,也许这就是它没有返回预期结果的原因。
In your test, you pass the parseInt method a number, not a string, maybe that's why it doesn't return the expected result.
试试
parseInt('0000022115', 10)
而不是
parseInt(0000022115, 10)
对我来说确实会返回221115.
that does return 221115 for me.
这篇关于Javascript,为什么被视为八进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!