0

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
6
  • 3
    Don'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. Commented Oct 15, 2015 at 20:15
  • no i need solution for this. I know how to do without zeroes Commented 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. Commented 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... Commented Oct 15, 2015 at 20:16
  • 1
    The exact reason is because that's how JavaScript decimal notation works. Commented Oct 15, 2015 at 20:21

2 Answers 2

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
3
  • yes ofcourse this is what my expected output thank you. Commented 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 :) Commented Oct 15, 2015 at 20:39
  • if u know the full answer please post me @Pointy Commented Oct 15, 2015 at 20:58
0

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 }

answered Oct 15, 2015 at 20:16
1
  • I dont want the answer in string i need the reason. Commented Oct 15, 2015 at 20:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.