2

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?

4 Answers 4

9

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?

Sign up to request clarification or add additional context in comments.

2 Comments

The statement: "JavaScript does not have keyed arrays" - is false. Arrays are objects and all native objects can have properties.
I changed the language from "keyed" to "associative" to be clearer.
2
  • 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;

Comments

1

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

2 Comments

Well that syntax is actually wrong; the equals signs should be colons.
Oops, you're right...I've been using too many languages at once. ;)
1

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.

2 Comments

There is no need to use if(true); {r=1, g=4, b=6} is a valid statement.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.