According to the official JavaScript documentation you can define object literal property names using integers:
Additionally, you can use a numeric or string literal for the name of a property.
Like so:
me = { name: "Robert Rocha", 123: 26, origin: "Mexico" }
My question is, how do you reference the property that has an integer as a name? I tried the usual me.123
but got an error. The only workaround that I can think of is using a for-in
loop. Any suggestions?
According to the official JavaScript documentation you can define object literal property names using integers: Additionally, you can use a numeric or string literal for the name of a property.
Against what many think, JavaScript object keys cannot be Number, Boolean, Null, or Undefined type values. Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.
Each key in your JavaScript object must be a string, symbol, or number.
To get object property name with JavaScript, we use the Object. keys method. const result = Object. keys(myVar); console.
You can reference the object's properties as you would an array and use either me[123]
or me["123"]
Dot notation only works with property names that are valid identifiers. An identifier must start with a letter, $, _ or unicode escape sequence. For all other property names, you must use bracket notation.
In an object literal, the property name must be an identifier name, string literal or numeric literal (which will be converted to a string since property names must be strings):
var obj = {1:1, foo:'foo', '+=+':'+=+'}; alert(obj[1] + ' ' + obj.foo + ' ' + obj['+=+']); // 1 foo +=+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With