1

i have created an object with the content of points and the mark you will get with

marks: {
                900: 1.0,
                822: 1.1,
                804: 1.2,
                786: 1.3,
                768: 1.4,
                750: 1.5,
                732: 1.6,
                714: 1.7,
                696: 1.8,
                678: 1.9,
                660: 2.0,
                588: 2.4,
                570: 2.5,
                552: 2.6,
                534: 2.7,
                516: 2.8,
                498: 2.9,
                480: 3.0,
                462: 3.1,
                444: 3.2,
                426: 3.3,
                408: 3.4,
                390: 3.5,
                372: 3.6,
                354: 3.7,
                336: 3.8,
                318: 3.9,
                300: 4.0
            },

if i show the object in the console the output will be

Object { 300=4, 318=3.9, 336=3.8, more...}

you can see it live on http://jsfiddle.net/Sx4Z2/

whats wrong and why is there an order in an object?

JuKe
  • 663
  • 2
  • 7
  • 20
  • 2
    I guess it's interpreted as an array with numeric indices. If you want to prevent ordering, try calling the elements e.g. `i318, i300` etc. (although it could be that the console always orders its properties by name) – Pekka Oct 28 '13 at 18:21
  • why it is an array? mark = {} => object – JuKe Oct 28 '13 at 18:22

3 Answers3

4

If the order is important for you, you should use an array. You can't trust property order in JavaScript objects. In your case, I'd use something like:

[
    {key: 900, value: 1.0},
    {key: 822, value: 1.1},
    // ...
]

Take a look at this question: Does JavaScript Guarantee Object Property Order?

Community
  • 1
  • 1
Guilherme Sehn
  • 6,727
  • 18
  • 35
2

ECMA-262 does not specify the ordering of keys in objects. Please note the following, however:

  1. Almost every JavaScript engine does retain key order anyway.
  2. ... unless those keys are integers, in which case they usually don't.

So, in your case, you should be able to provide predicable behavior (although not based on any standard) if you prefix your keys with some non-alpha string.

jmar777
  • 38,796
  • 11
  • 66
  • 64
  • 2
    Relying on undocumented behaviour is usually a bad idea. – Darkhogg Oct 28 '13 at 18:24
  • 1
    The behavior isn't actually "predicable". It could change with any new version. *Don't* rely on it! – gen_Eric Oct 28 '13 at 18:25
  • 2
    I agree that it's probably not advisable. However, virtually all browser vendors have recognized that there are enough sites "in the wild" that rely on this behavior such that they support it as a feature. Can't seem to find it right now, but I've even seen a bug filed against V8 for a regression here, which was subsequently fixed. – jmar777 Oct 28 '13 at 18:27
2

It doesn't reorder itself - a JavaScript object has no specified order. If you need order, use an array.

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100