How to get the value of key a and 'a' in javascript?
var obj = {a:1,'a':2}
A property is a “key: value” pair, where key is a string (also called a “property name”), and value can be anything. We can imagine an object as a cabinet with signed files. Every piece of data is stored in its file by the key. It's easy to find a file by its name or add/remove a file.
Properties in JavaScript are defined as pairs of keys and values. Keys can be generally thought of as the names of the values stored within JavaScript objects.
The first key a
will be overwritten by the second 'a'
.
obj.a
will return 2.
If your key name is a valid Javascript identifier or a number, Javascript will allow you to omit the quotes in key names. In practice, however, it's probably better to train yourself to always use quotes, to avoid confusion like this, and also because JSON requires them.
You can't - they are same key, and that initialiser will create an object with a single element 'a' with value '2'. Try this:
var obj = {a:1,'a':2};
for ( var i in obj )
{
alert(i + '=' + obj[i] );
}
And you'll just get "a=2' in response.
obviously, 'a'
is the one-character string with a lowercase a as content; but what do you expect to be the other key? if you want it to be the value of a variable called a
, then the curly braces syntax won't help you. Unlike Python, this syntax assumes the keys are strings, and quotes are optional.
You'd have to do something like this:
var a = 'givenkey'
var obj = {}
obj[a] = 1
obj['a'] = 2
this would create an object equivalent to:
var obj = {'givenkey':1, 'a':2}
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