Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of key a and 'a' in javascript

Tags:

javascript

How to get the value of key a and 'a' in javascript?

var obj = {a:1,'a':2}
like image 785
omg Avatar asked Sep 09 '09 14:09

omg


People also ask

What is key and value in JavaScript?

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.

What is a key in JavaScript?

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.


3 Answers

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.

like image 135
Kenan Banks Avatar answered Oct 04 '22 15:10

Kenan Banks


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.

like image 36
Paul Dixon Avatar answered Oct 04 '22 14:10

Paul Dixon


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}
like image 22
Javier Avatar answered Oct 04 '22 13:10

Javier