I have an array contains two elements [0010, 0011];
like this. i need the same two elements in the output also.
var a = [0010, 0011];
for (var i=0;i<a.length;i++){
console.log(a[i]); // output is 8, 9 (expected output 0010,0011)
}
asked Oct 15, 2015 at 20:14
-
3Don't put the zeros on the front of the values. That's just basic JavaScript syntax. (Also some other languages.) Or make the values strings, if what they look like is more important than their numeric values.Pointy– Pointy2015年10月15日 20:15:18 +00:00Commented Oct 15, 2015 at 20:15
-
no i need solution for this. I know how to do without zeroeshtoniv– htoniv2015年10月15日 20:16:00 +00:00Commented Oct 15, 2015 at 20:16
-
Then make them strings. There's nothing you can do to tell JavaScript not to interpret a numeric constant the way it thinks it should.Pointy– Pointy2015年10月15日 20:16:33 +00:00Commented Oct 15, 2015 at 20:16
-
If you want that exact representation, store strings in the array instead. A number is a number is a number, the only thing that differs is the string representation of them...folkol– folkol2015年10月15日 20:16:48 +00:00Commented Oct 15, 2015 at 20:16
-
1The exact reason is because that's how JavaScript decimal notation works.Sterling Archer– Sterling Archer2015年10月15日 20:21:13 +00:00Commented Oct 15, 2015 at 20:21
2 Answers 2
You can convert the numbers to strings for display using the toString
function.
console.log(a[i].toString(8)); // displays in base 8 (octal)
This way they stay in numeric form in your array, so you can still do math operations on them.
answered Oct 15, 2015 at 20:20
-
yes ofcourse this is what my expected output thank you.htoniv– htoniv2015年10月15日 20:22:05 +00:00Commented Oct 15, 2015 at 20:22
-
@htoniv you said your "expected output" included the leading zeros, but this won't give you those. If that's OK, then I am happy that you have found your answer :)Pointy– Pointy2015年10月15日 20:39:09 +00:00Commented Oct 15, 2015 at 20:39
-
if u know the full answer please post me @Pointyhtoniv– htoniv2015年10月15日 20:58:49 +00:00Commented Oct 15, 2015 at 20:58
Use String as javascript interprets numeric constants as octal.
var a = ["0010", "0011"];
for (var i=0;i<a.length;i++){
console.log(a[i]); // expected output 0010,0011
}
-
I dont want the answer in string i need the reason.htoniv– htoniv2015年10月15日 20:20:00 +00:00Commented Oct 15, 2015 at 20:20
lang-js