Javascript map function converting values to decimal

Viewed 578

I have a array like this.

var elements=[5614,6619,7220,7320,7830,8220,0111,0112,0113,0142,0149]

Am converting every element to string so as to use with jquery autocomplete. Am using .map function to do this.

elements = elements.map(String);

output is

["5614", "6619", "7220", "7320", "7830", "8220", "73", "74", "75", "98", "149"]

Function is taking 0111,0112,0113,0142 all these values as Octal values and converting them to decimal.

I don't want this conversation and want to preserve leading Zero also , How can I do this , please help.

1 Answers

Function is taking 0111,0112,0113,0142 all these values as Octal values and converting them to decimal.

It's not the function doing that, it's this:

var elements=[5614,6619,7220,7320,7830,8220,0111,0112,0113,0142,0149]

In loose mode, if you start a number with a 0 followed by a series of octal digits, it's octal. That's why 010 === 8 is true:

console.log(010 === 8); // true

And heaven help us, but if you have a 0 followed by a number with non-octal decimal digits (8 or 9), it's decimal, which is why 011 === 09 and 9 === 09 are true:

console.log(011 === 09); // true
console.log(9 === 09);   // true

The solution is:

  1. Use strict mode ("use strict";). Both legacy octal literals (010) and legacy non-octal decimal literals (08) are disallowed in strict mode. (If you need to write octal, you can, with the newer 0o10 format — that's the number eight.)

  2. Don't write leading zeros on numbers (with the possible exception of a 0 just prior to a . in a fractional number less than one)

You can't fix elements after the fact (because it's impossible to know, once they're numbers, which ones were incorrectly written in octal), you have to fix it at the point you're creating it, e.g.:

var elements=[5614,6619,7220,7320,7830,220,111,112,113,142,149]
Related