4

Why do I get this error with this code: Uncaught SyntaxError: Unexpected token { on line 1.

var cube_points = {
    {'x' : 100, 'y' : 100, 'z' : 100},
    {'x' : 100, 'y' : 100, 'z' : -100},
    {'x' : -100, 'y' : 100, 'z' : -100},
    {'x' : -100, 'y' : 100, 'z' : 100},
    {'x' : 100, 'y' : -100, 'z' : 100},
    {'x' : 100, 'y' : -100, 'z' : -100},
    {'x' : -100, 'y' : -100, 'z' : -100},
    {'x' : -100, 'y' : -100, 'z' : 100}
};
ErikE
  • 48,881
  • 23
  • 151
  • 196
seymar
  • 3,993
  • 6
  • 25
  • 30

2 Answers2

7

What you have is not a valid javascript object definition. {} denotes object, so inside you should have properties, not other {}. What you need is an array which is denoted with []:

var cube_points = [
    {'x' : 100, 'y' : 100, 'z' : 100},
    {'x' : 100, 'y' : 100, 'z' : -100},
    {'x' : -100, 'y' : 100, 'z' : -100},
    {'x' : -100, 'y' : 100, 'z' : 100},
    {'x' : 100, 'y' : -100, 'z' : 100},
    {'x' : 100, 'y' : -100, 'z' : -100},
    {'x' : -100, 'y' : -100, 'z' : -100},
    {'x' : -100, 'y' : -100, 'z' : 100}
];

which you could then access like this:

cube_points[2].y
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
7

Your outer object's elements have values but no keys. If you want an array of cube points, use the square bracket to denote an array literal:

var cube_points = [
    {'x' : 100, 'y' : 100, 'z' : 100},
    {'x' : 100, 'y' : 100, 'z' : -100},
    {'x' : -100, 'y' : 100, 'z' : -100},
    {'x' : -100, 'y' : 100, 'z' : 100},
    {'x' : 100, 'y' : -100, 'z' : 100},
    {'x' : 100, 'y' : -100, 'z' : -100},
    {'x' : -100, 'y' : -100, 'z' : -100},
    {'x' : -100, 'y' : -100, 'z' : 100}
];

If you want an object, give the items a key. This could be numbers or letters or even objects:

var cube_points = {
    1: {'x' : 100, 'y' : 100, 'z' : 100},
    2: {'x' : 100, 'y' : 100, 'z' : -100},
    'q': {'x' : -100, 'y' : 100, 'z' : -100},
    'z': {'x' : -100, 'y' : 100, 'z' : 100},
    '25': {'x' : 100, 'y' : -100, 'z' : 100},
    '26': {'x' : 100, 'y' : -100, 'z' : -100},
    10: {'x' : -100, 'y' : -100, 'z' : -100},
    11: {'x' : -100, 'y' : -100, 'z' : 100}
};

Obviously, using an object necessitates some kind of orderly system of key selection. Since your points aren't easily named, you're better off using an array. But I wanted to show what object literal notation would look like.

ErikE
  • 48,881
  • 23
  • 151
  • 196
  • I honestly think starting at `0` in the object is more consistent. – pimvdb May 22 '11 at 08:29
  • It's an object. You can use letters or numbers or objects as keys. But just to put a lid on the critics, I'll make some adjustments. – ErikE May 22 '11 at 19:05