-1

I am trying to use a variable to select from an array:

This works:

var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};

function One() {
   alert(myarray.bricks);
}

But this does not work:

var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};

var myvalue = "bricks"

function Two() {
   alert(myarray.myvalue);
}

How do I do this properly? Here is a fiddle to show what I am trying to accomplish: https://jsfiddle.net/chrislascelles/xhmx7hgc/2/

0

3 Answers 3

1

Use the [] notation.

var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};

function One() {
       alert(myarray.bricks);
}


var myvalue = "bricks"  //supplied here to make example work

function Two() {
       alert(myarray[myvalue]);
}

Demo

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

Comments

1

The variable is not an array, it's an object.

To access an element from object using variables you should use Bracket Notation like bellow

alert(myarray[myvalue]);

Fiddle

1 Comment

What's next? Answering a question about using + to add numbers, and providing a fiddle to show how that works?
1

The only thing you are lacking is the syntax. Here is how it works:

function Two() {
   alert(myarray[myvalue]);
}

In javascript, it means the same thing to write these two:

var a = {};
a.foo = "hello";
a["bar"] = "world";

a.bar; // world;
a["foo"]; // hello;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.