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

      

+3


source to share


3 answers


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" };

      

+7


source


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

0


source


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[ζˆ‘];

      

0


source







All Articles