views:

106

answers:

4

Hey all. Newbie JavaScript question here. I have an array: {r=1, g=4, b=6} How do i go about getting the value of each (r,g,b) into a separate variable?

+2  A: 
  • That's not an array
  • That's almost an object constant, but you need ":" instead of "="
  • The values already are in separate variables, or would be if the syntax was OK

That's the syntax for instantiating an "object constant" and populating it with properties and values. If you assign that value (the whole thing) to another variable, then you'll be able to get at the properties.

var rgb = { r: 1, g: 4, b: 6};
var rByItself = rgb.r;
Pointy
A: 

In Javascript, {r:1, g:4, b:6} would be an object. Let's pretend your object is declared as such:

var obj = {r:1, g:4, b:6};

Then you could retrieve the values of r, g, and b in two ways.

Method 1:

var red = obj.r;
var green = obj.g;
var blue = obj.b;

Method 2:

var red = obj['r'];
var green = obj['g'];
var blue = obj['b'];
Matt Huggins
Well that syntax is actually wrong; the equals signs should be colons.
Pointy
Oops, you're right...I've been using too many languages at once. ;)
Matt Huggins
+5  A: 

JavaScript does not have associative arrays. So this is legal:

var my_rgb_arr = [1, 4, 6]

Or this can be legal:

var my_rgb_obj = { r: 1, g: 4, b: 6 };

To access the array:

my_rgb_arr[0]; // r
my_rgb_arr[1]; // g
my_rgb_arr[2]; // b

And the object:

my_rgb_obj.r; // r
my_rgb_obj.g; // g
my_rgb_obj.b; // b

Which are you dealing with?

artlung
The statement: "JavaScript does not have keyed arrays" - is false. Arrays are objects and all native objects can have properties.
Garrett
I changed the language from "keyed" to "associative" to be clearer.
artlung
+1  A: 

What you have: {r=1, g=4, b=6} could only be interpreted as a block in ECMAScript. It is therefore not an Array.

Arrays and Objects Example:

var myArray = [1, 4, 6];
var myObject = { r:1, g:4, b:6 };

Block Example:

var r, g, b;
if(true) 
  {r=1, g=4, b=6};

Code should be executable, as transmitted and the outcome of that code posted.

Garrett
There is no need to use `if(true)`; `{r=1, g=4, b=6}` is a valid statement.
Gumbo
Yes, <code>{r=1, g=4, b=6}</code> is a valid statement (thanks). It does not, however, go with what the question is describing.
Garrett