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]);
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]);
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' };
{}
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.)