0

Hello i'm begignner at javascript, I wrote the code below and get this error in my console "SyntaxError: Unexpected token ,"

var tab1=[{0,2,4,6,8},{1,3,5,7}];



console.log(tab1[0][0]); 
hopo
  • 67
  • 1
  • 3
  • 8

2 Answers2

2

Please change the curly to square brackets:

var tab1 = [[0, 2, 4, 6, 8], [1, 3, 5, 7]];

[] are used for arrays, {} are used for objects.

Examples:

array = ['a', 'b', 'c'];
object = { property: 'one', key: 'two' };
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I want exemple the object with (loop for ) and also array ? please ? – hopo Feb 18 '16 at 14:38
  • 1
    please read T. J. Crowder's superb answer for looping arrays: http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476#9329476 – Nina Scholz Feb 18 '16 at 14:43
1

{} is for creating objects; it expects key: value pairs inside, which are called property initializers.

[] is for creating arrays.

So if you want to create an array of arrays (JavaScript doesn't have two-dimensional arrays, but arrays of arrays work just as well), use nested []:

var tab1=[[0,2,4,6,8],[1,3,5,7]];

Just for completeness, here's an example of an object rather than array:

var obj = {
    question: "Life, the Universe, and Everything",
    answer: 42
};

The reason for the error is that you just had 0,2 and it was expecting a : after the 0. (Literal numbers are valid object keys, which is why the 0 wasn't the problem.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I want exemple the object with (loop for ) and also array ? please ? – hopo Feb 18 '16 at 14:23
  • @hopo: I'm not sure what you mean, but if you're talking about looping through arrays, I wrote a fairly comprehensive answer on it [here](http://stackoverflow.com/a/9329476/157247). (It's a long answer, but really you only need to look at examples 1 and 2.) – T.J. Crowder Feb 18 '16 at 14:39