While typing the value {2,4,45,50} on console displays 50, but assigning the {2,4,45,50} to variable getting the error
var a = {2,4,45,50}
Uncaught SyntaxError: Unexpected number
What is the concept on this.
CodePudding user response:
its [] for arrays, the console just treats your {} like a block and gives you the last value – skara9
As Skara mentioned, []
is for arrays. {}
is for tables, so when you assign it to a variable since it's a table it's expecting a key and value, for example: {a: 1, b:2, 3:4}
. If you want an array then change {}
to []
, otherwise, you should assign a key and value for the table.
If you would like to log a specific value of an array you can do so using an index, index starts from 0 to the number of values. For example:
var a = [2,4,45,50]
console.log(a[0])
//Expected output is 2
If you wanted to use a table and log the value of the first key, which in this case would be a
, then you would do:
var test = {a:2, b:4, c:45, d:50}
console.log(test.a)
//Expected output is 2 because 2 is assigned to a
You could also just log the whole array and/or table.
CodePudding user response:
var a = {
2: 2,
3: 3,
4: 4,
50: 50,
}
console.log(a[50]);