[英]How can i ignore the javascript convert leading zero to octal?
I want to convert number
to string
, buti have a problem about javascript convert number that have leading zero to octal.我想将number
转换为string
,但是关于 javascript 将前导零转换为八进制的数字有问题。
I have a list of object like this我有一个像这样的 object 列表
const ids = [
{ _id : 1236 },
{ _id : "abc123" },
{ _id : 012019 },
{ _id : 000010 },
{ _id : 001230 }
{ _id : 00000000000000 }
]
and i want to convert all of id in object to string
like this我想将 object 中的所有 id 转换为这样的string
[
{ _id : "1236" },
{ _id : "abc123" },
{ _id : "012345" },
{ _id : "000010 },
{ _id : "001230" },
{ _id : "00000000000000" }
]
So, i write a function like this所以,我像这样写了一个 function
updateIds = () => ids.map(i => {
i._id = i._id.toString()
return i
})
updateIds()
But the result of this function is..但是这个 function 的结果是..
[
{ _id: '1236' },
{ _id: 'abc123' },
{ _id: '012019' },
{ _id: '8' },
{ _id: '664' },
{ _id: '0' }
]
how can i ignore javascript convert 000010
and 001230
to octal?我如何忽略 javascript 将000010
和001230
转换为八进制?
Ps.附言。 I think i cant use pad
function to write leading zero because value of _id
is dynamic.我想我不能使用pad
function 写前导零,因为_id
的值是动态的。 i don't know that length.我不知道那个长度。
You have to define the base you want to use in the toString
call.您必须定义要在toString
调用中使用的基数。
If you want the ids to be parsed as base 10, then called toString(10)
.如果您希望将 id 解析为以 10 为底,则调用toString(10)
。 It's impossible to do the padding to preserve the length because numbers are numbers, so leading zeros are ignored.不可能通过填充来保留长度,因为数字是数字,因此忽略前导零。 You can pad to a fixed length, for all the ids:对于所有 id,您可以填充到固定长度:
updateIds = () => ids.map(i => {
i._id = i._id.toString(10).padStart(9, '0');
return i
})
Use Constructor call Number("001230")
.使用构造函数调用Number("001230")
。 It will convert all numbers to base 10
only, so you won't have the octal
conversion problem它将所有数字仅转换为以base 10
,因此您不会遇到octal
转换问题
const ids = [
{ _id : 1236 },
{ _id : "abc123" },
{ _id : 012019 },
{ _id : 000010 },
{ _id : 001230 },
{ _id : 00000000000000 }
];
let ans = [];
ids.forEach((val)=>{
let obj = {};
obj._id = Number(val["_id"]);
ans.push(obj);
})
console.log(ans);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.