Using Chinese as an Object Key
How can I use a Chinese character or number as a key for an object like this:
var obj = { ζ: 'me', 20: 'you' };
console.log(obj.ζ); // me
console.log(obj[ζ]); // -> Reference Error: ζ is not defined
console.log(obj[20]); // you
console.log(obj.20); // ->Syntax Error: Unexpected number
source to share
To use dot notation on an object, the key must be a valid JavaScript identifier. Mozilla Documentation Network :
You can use ISO 8859-1 or Unicode letters like Γ₯ and ΓΌ in identifiers. You can also use Unicode escape sequences as characters in identifiers.
Indeed, in Firefox, this is valid syntax:
var x = { ζ: 5 };
x.ζ
var ζ = 42;
console.log(ζ);
Chrome accepts this too.
In case your browser (or the browser that your visitors use) does not follow strict adherence to standards, you can use:
var obj = { 'ζ': 'me', 20: 'you' };
console.log(obj['ζ']);
It's worth noting that you can use arbitrary strings as object keys, even if they are not valid JavaScript identifiers (for example thay contain spaces and / or punctuation marks):
var obj = { " ": "space", ";": "semicolon" };
source to share
It is generally bad practice to include ANSI characters in JS source code in .html * or .js files as they can be lost while editing the files (i.e. when saving as ANSI instead of Unicode) or when switching hosting OS.
Consider converting these characters to their Unicode equivalent using the JavaScript escape () method (for example, escape ('ζ') returns: "% u6211").
Check the following link for full details: W3C Symbol Symbols in Markup and CSS
source to share
Your confusion is about what obj.ζ
works but obj[ζ]
not? On the other hand, obj[20]
does?
Well 20
- a value literal. You can write 20
anywhere to create a numeric value 20
. On the other hand, ζ
it is not a valid literal for anything. If you want to create a string value "ζ" you need to write 'ζ'
. On the other hand, if you want to be ζ
the name of a variable, you need to declare the variable with var ζ
. The error you are seeing is telling you there is no variable ζ
.
On the other hand, it obj.20
is invalid syntax because 20
it is not a valid variable name. The reason for this is that numeric literals create numbers, so the syntax becomes ambiguous if they can also be used as variable names. Does it foo = 20
mean you want to assign a number 20 foo
or a value to a 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 will do pretty well:
var ζ = 'ζ';
obj[ζ];
source to share