【问题标题】:Get object element from a defined string [duplicate]从定义的字符串中获取对象元素[重复]
【发布时间】:2017-02-01 00:17:34
【问题描述】:

如何通过定义字符串从对象中获取数据?

案例:

  var data = [
  {name:"Sharma",country:"India"},
  {name:"Udin",country:"Indonesia"},
  {name:"John Carter",country:"Mars"}
  ];

  getData(data,"country");

  function getData(data,element){
    console.log(data[1].element);
  }

我想得到国家,但结果是未定义,如何解决这个问题?

【问题讨论】:

    标签: javascript arrays function object


    【解决方案1】:

    你需要知道索引和属性

    function getData(data,index,element){
        console.log(data[index][element]);
    }
    
    getData(data,1,"country");
    

    【讨论】:

    • 您仍然需要对数组进行索引(data 是一个数组)-也许他应该有一个参数来指定索引...?
    • 你说得对,我看错了问题。**已更新**
    【解决方案2】:
    function getData(data,element){
        console.log(data[1][element]);
      }
    

    这是使用字符串键访问值的正确方法。

    【讨论】:

    • 谢谢老兄,太棒了
    猜你喜欢
    • 1970-01-01
    • 2019-04-30
    • 2018-04-25
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2011-10-27
    相关资源
    最近更新 更多