【发布时间】:2019-05-02 19:56:41
【问题描述】:
我将一个 id 作为参数传递给一个 javascript 函数,因为它来自 UI,它被填充为零。但它似乎有(也许)“奇怪”的行为?
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
我如何确保它们解析为正确的数字? (十进制)
编辑:
只是让它更清楚:
这些数字来自服务器并且是零填充字符串。我正在为每个人制作一个删除按钮。
喜欢:
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 which is 22115's octal
仍然解析为八进制
【问题讨论】:
-
不要使用零填充数字,而是使用空格。
-
为什么UI左边用0填充?
-
在脚本中使用
"use strict"指令可能是个好主意。这将导致任何使用八进制文字都会引发错误,并且应该使调试变得更容易! -
关于
parseInt(0000022115, 10):您仍然传递一个数字作为第一个参数,这使得JavaScript 首先转换数字,然后将其传递给parseInt。而是传递一个字符串。 -
如果您从
'<a...</a>'字符串创建一个新元素,那么您需要将字符串的value部分用引号括起来。'<a href="#" onclick="deleteme(\''+value+'\')">'
标签: javascript