【问题标题】:Have a variable select from an array [duplicate]从数组中选择一个变量[重复]
【发布时间】:2015-05-24 14:21:48
【问题描述】:

我正在尝试使用变量从数组中进行选择:

这行得通:

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);
}

我该如何正确地做到这一点?这是一个小提琴来展示我想要完成的事情:https://jsfiddle.net/chrislascelles/xhmx7hgc/2/

【问题讨论】:

    标签: javascript object properties


    【解决方案1】:

    使用[] 表示法。

    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

    【讨论】:

      【解决方案2】:

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

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

      alert(myarray[myvalue]);
      

      Fiddle

      【讨论】:

      • 下一步是什么?回答有关使用 + 添加数字的问题,并提供一个小提琴来展示它是如何工作的?
      【解决方案3】:

      您唯一缺少的是语法。以下是它的工作原理:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-22
        • 1970-01-01
        • 1970-01-01
        • 2017-05-03
        • 1970-01-01
        • 1970-01-01
        • 2013-07-17
        相关资源
        最近更新 更多