Parse Javascript Array

I have an array: {r = 1, g = 4, b = 6} How do I get the value of each (r, g, b) in a separate variable?

+2


a source to share


4 answers


JavaScript has no associative arrays. So this is legal:

var my_rgb_arr = [1, 4, 6]

      

Or it might 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

      

What are you dealing with?

+9


a source


  • This is not an array
  • It's almost a constant object, but you need ":" instead of "="
  • The values ​​are already in separate variables or would be if the syntax was OK

This is the syntax for creating an "object constant" and populating it with properties and values. If you assign this value (all of this) to another variable, you can get the properties.



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

      

+2


a source


In Javascript {r:1, g:4, b:6}

will be an object. Imagine your object is declared as such:

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

      

Then you can get 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'];

      

+1


a source


What you have: {r=1, g=4, b=6}

can only be interpreted as a block in ECMAScript. Hence it is 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};

The code must be executable as passed and the output of that code.

+1


a source







All Articles