Reputation: 454
I am in bit of a puzzle, recently I had worked on a project where use of javascript was necessary. Everything is working fine I just need to know how does it work
eg : I had a dynamic variable count
, which use to get some value, lets say I get the value as var count = 6;
Now when I put this in array {count : count }
I get the output as {count : 6}
Now my doubt is the output should have been { 6 : 6}
as count should have been replaced with its value but it didn't happen so. Why is happening ? and how is this working properly ?
Upvotes: 0
Views: 43
Reputation: 1384
In JavaScript associative arrays (or most associative arrays for that matter), the left side is the key, and the right side is the value. -> {key:value}
When you put {count:count}
when you have a count
variable beforehand (let's say its value is 10), what will happen is it will be read as {count:10}
.
The left-hand side, or the key, is not a variable, but a constant.
Upvotes: 0
Reputation: 19523
The JavaScript object initialisation syntax lets you use bare words. If you do this:
{ foo: 6, bar: 12 }
It's equivalent to this:
{ 'foo': 6, 'bar': 12 }
What you want is to assign directly, like so:
var foobar = {};
foobar[foo] = 6;
foobar[bar] = 12;
Upvotes: 0
Reputation: 3669
The key value pairs treat the key as a literal and the value as a variable.
so:
var count = 6;
var o = {count: count}; // results in {count: 6}
but to use a variable as the key, you can do this:
var count = 6;
var o = {};
o[count] = count; // results in: {6: 6}
Upvotes: 1