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?
- 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;
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'];
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?
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.