Your confusion is that obj.我
works but obj[我]
doesn't? On the other hand, obj[20]
does?
Well, 20
is a value literal. You can write 20
anywhere to create the number value 20
. On the other hand, 我
is not a valid literal for anything. If you want to create the string value "我", you need to write '我'
. On the other hand, if you want 我
to be a variable name, you need to declare the variable beforehand with var 我
. The error you're seeing is telling you that there's no variable 我
defined.
On the other hand again, obj.20
is invalid syntax since 20
is not a valid variable name. The reason for that is that numeric literals create numbers, hence the syntax would become ambiguous if they could also be used as variable names. Does foo = 20
mean you want to assign the number 20 to foo
, or the value of the variable 20
? Hence, numeric literals are reserved for numbers, period.
obj.我 → requires valid symbol name, 我 is valid symbol name
obj[我] → requires valid *value*, 我 is not value literal nor declared variable
obj.20 → requires valid symbol name, 20 is not valid symbol name
obj[20] → requires valid *value*, 20 is valid value literal
This would work just fine:
var 我 = '我';
obj[我];