-1

First, I am a beginner of javascript. Please understand asking this simple question.. (looks simple)

I was making a membership related webpage and encountered an error.. I was learned that to access the element of an object, I can use '.'(dot) so I coded like, It was a bit long object(json type contents) but.. to sum up,

dict1 = {'a':1, 'b':2, 'c':3};

dict2 = {1:'a', 2:'b', 3:'c'}

dict1.a result: 1

dict2.1 result: Uncaught SyntaxError: Unexpected number

so the point is, Someone may think, "if you can see the elements, why would you access the element by '.'(dot). if you already know it can cause the error." but the data is user input and users can input any data as they wish.

Javascript provides '.'(dot) operator for Object but not working for number Element??

or do I use the dot in wrong way?

Tom
  • 1
  • 1
  • Please read this answer https://stackoverflow.com/a/9304820/7301881 – Mean Coder Nov 08 '21 at 06:06
  • @MeanCoder—that answer is about JSON, which doesn't tell the OP why they have their issue or how to fix it. ECMAScript object literals allow computed property names, not just plain strings. And the issue is with the use of dot notation, not the object literal itself. – RobG Nov 08 '21 at 06:21
  • Wow, I did not know that JSON allows strings only as its key. Thank you very much for your comment! have a nice day. – Tom Nov 08 '21 at 06:39

2 Answers2

1

If you use dot notation, your key must be a valid identifier (start with a letter, $ or _). So in this case you would need to use dict2['1'].

pso
  • 513
  • 1
  • 16
  • Also worth noting that ` {1:'a'}` is processed as `{'1':'a'}`, i.e. the number 1 is converted to a string when assigned as a property name, hence the string '1' must be used to access the value. :-) – RobG Nov 08 '21 at 06:23
  • Thank you for your comment, Right, JSON allows strings only as its key. now I can see why. – Tom Nov 08 '21 at 06:42
  • This is not related question but... I did not find the same question but found that my question is duplicated as stack overflow informed me of it. Then, should I remove my question? pls, understand, I am a newbie hear =( – Tom Nov 09 '21 at 00:02
0

You can do something like this to get the values

// With the braces you can get the values even if the key is a number
let dict2 = {
  1: 'a',
  2: 'b',
  3: 'c'
}

console.log(dict2[1])

// Even if you want to access the values that are having keys like strings you can use the same operator
dict1 = {'a':1, 'b':2, 'c':3};

console.log(dict1['a'])
Tejesh Palagiri
  • 729
  • 4
  • 9
  • Thank you for your example, actually I already found the solution after I encountered the error and it is the same way just like you commented =), I just wanted to know what was wrong with that code and why that code printed the error. many thanks!! – Tom Nov 08 '21 at 06:48