从数组中获取变量 select

Have a variable select from an array

我正在尝试使用数组中的变量 select:

这个有效:

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

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

但这不起作用:

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

var myvalue = "bricks"

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

如何正确执行此操作?这是一个 fiddle 来展示我正在努力完成的事情:https://jsfiddle.net/chrislascelles/xhmx7hgc/2/

变量不是数组,而是对象。

要使用变量访问对象中的元素,您应该使用括号表示法,如下所示

alert(myarray[myvalue]);

Fiddle

你唯一缺少的就是语法。它是这样工作的:

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

在javascript中,写这两个意思是一样的:

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

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

使用 [] 表示法。

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