【问题标题】:Finding Keys in associative arrays with JavaScript使用 JavaScript 在关联数组中查找键
【发布时间】:2016-12-10 00:15:53
【问题描述】:

有了这个关联数组,我想找到一个特定的键:

var veggie_prices = new Array();
veggie_prices["serves6"] = 20;
veggie_prices["serves8"] = 25;
veggie_prices["serves10"] = 35;

如果我遍历数组,我可以通过以下方式找到值:

var x = veggie_prices[i].value;

但是应该如何找到密钥呢?

var y = veggie_prices[i].key;

【问题讨论】:

    标签: javascript arrays key associative-array


    【解决方案1】:

    要直接回答您的问题,请使用for..in 循环

    var veggie_prices = new Array();
    veggie_prices["serves6"] = 20;
    veggie_prices["serves8"] = 25;
    veggie_prices["serves10"] = 35;
    for (var i in veggie_prices) {
      console.log(i); // output: serves6, etc..
    }
    

    但是,为了清楚起见,javascript 没有关联数组。你所拥有的是一个数组类型的对象,除了普通的(虽然目前是空的)索引和其他原生数组属性/方法(例如.length.pop() 等)之外,你只是向它添加了几个属性..)

    【讨论】:

    • 只是为了添加上下文 - 目前,此列表使用单选按钮控件在列表上进行选择。为了找到带有 for 循环的选定单选按钮,我使用 .checked 方法和 .value 来获取值。使用 .key 没有产生密钥。不知道为什么。谢谢你的回答。
    【解决方案2】:

    为什么要使用数组?你可以用一个对象来代替吗?

    var veggie_prices = {};
    veggie_prices["serves6"] = 20;
    veggie_prices["serves8"] = 25;
    veggie_prices["serves10"] = 35;
    
    Object.keys(veggie_prices).forEach((key) => {
      console.log('Key is: ' + key);
      console.log('Value is: ' + veggie_prices[key]);
    });
    

    【讨论】:

    • Yes 将移动到对象。目前,此列表使用单选按钮控件在列表上进行选择。为了找到选中的单选按钮,我使用了 .checked 方法和 .value 来获取值。使用 .key 没有产生密钥。不知道为什么。谢谢你的回答。
    猜你喜欢
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 2010-12-07
    • 2011-08-18
    • 2011-01-01
    • 2012-11-03
    • 2016-11-25
    • 1970-01-01
    相关资源
    最近更新 更多