Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse Javascript Array

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?

like image 799
rhepungus Avatar asked Aug 12 '26 23:08

rhepungus


2 Answers

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?

like image 113
artlung Avatar answered Aug 14 '26 14:08

artlung


  • 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;
like image 29
Pointy Avatar answered Aug 14 '26 12:08

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!