-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/

user1218172
  • 193
  • 1
  • 12

3 Answers3

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

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
  • What's next? Answering a question about using `+` to add numbers, and providing a fiddle to show how that works? –  Mar 21 '15 at 04:34
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;
Ibu
  • 42,752
  • 13
  • 76
  • 103
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

Jashwant
  • 28,410
  • 16
  • 70
  • 105