javascript 在javascript中访问数组中的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12232918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:40:53  来源:igfitidea点击:

Access array in array in javascript

javascriptjquery

提问by Pankaj

I am getting a JSON reply, like following:

我收到 JSON 回复,如下所示:

[{
  "order_id": "12",
  "customer": "user user",
  "status": "Pending",
  "date_added": "02\/09\/2012",
  "total": "0.00",
  "action": [{
    "text": "View",
    "href": "http:\/\/localhost\/oc\/admin\/index.php?route=sale\/order\/info&token=92a80574e5fcbf3e2d021404cfaae1a4&order_id=12"
  }]
}]

have a look on action key, it's value is again an array. I am trying to get action key values by following code but it is showing undefined to me

看看操作键,它的值又是一个数组。我正在尝试通过以下代码获取操作键值,但它向我显示未定义

function (data) {
  if (data) {
    for (var i = 0; i < data.length; i++) {
      $('div.dashboard-content table.list tbody tr:first').before(
        '<tr id="' + 
        data[i]['order_id'] + 
        '"><td class="right">' + 
        data[i]['order_id'] + 
        '</td><td class="left">' + 
        data[i]['customer'] + 
        '</td><td class="left">' + 
        data[i]['status'] + 
        '</td><td class="left">' + 
        data[i]['date_added'] + 
        '</td><td class="right">' + 
        data[i]['total'] + 
        '</td><td class="right"> [<a href="' + 
        data[i]['action']['href'] + '">' + 
        data[i]['action']['text'] + 
        '</a>]</td></tr>'
      );
    }
  }
}

Can somebody help me.? Thanks in advance.

有人可以帮我吗。?提前致谢。

采纳答案by Jo?o Silva

Like you said, actionis an array. Thus, you can't access it using data[i]['action']['href']. You have to use a subscript to indicate the position of the array that you want. For example, to access the first position, you'd use:

就像你说的,action是一个数组。因此,您无法使用data[i]['action']['href']. 您必须使用下标来指示所需数组的位置。例如,要访问第一个位置,您可以使用:

var href = data[i].action[0].href;
var text = data[i].action[0].text;

回答by Paul

actionis an array containing an object with a property called text. Change:

action是一个数组,其中包含一个具有名为 text 的属性的对象。改变:

data[i]['action']['text']

to:

到:

data[i]['action'][0]['text']