JavaScript:如何从多维数组中获取值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10271312/
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-08-24 00:36:50  来源:igfitidea点击:

JavaScript: How to Get the Values from a Multi-Dimensional Array?

javascriptarraysmultidimensional-array

提问by kentrenholm

I'm trying to get the values from a multi-dimensional array. This is what I have so far.
I need the value of 99 and the image when I select the first option in the array, e.g. "Billy Joel".

我正在尝试从多维数组中获取值。这是我到目前为止。
当我选择数组中的第一个选项时,我需要 99 的值和图像,例如“Billy Joel”。

var concertArray = [
    ["Billy Joel", "99", "equal.png"],
    ["Bryan Adams", "89", "higher.png"],
    ["Brian Adams", "25", "lower.png"]
];

function populate(){
    for(i = 0; i < concertArray.length; i++){
        var select = document.getElementById("test");
        select.options[select.options.length] = new Option(concertArray[i][0], concertArray[i][1]);
    }
}

回答by

You can try to transform the multi-dimensional array to an array of objects like this:

您可以尝试将多维数组转换为这样的对象数组:

var concertArray = [
    {name: "Billy Joel", value: 99, image: "equal.png"},
    {name: "Bryan Adams", value: 89, image: "higher.png"},
    {name: "Brian Adams", value: 25, image: "lower.png"}
];

Then you can access the items in the array like regular objects:

然后您可以像访问常规对象一样访问数组中的项目:

var concertName = concertArray[0].name;
var concertPrice = parseFloat(concertArray[0].value);
var concertImage = concertArray[0].image;

回答by mgraph

99 => concertArray[i][1]image => concertArray[i][2]

99 =>concertArray[i][1]图像 =>concertArray[i][2]

回答by David Hellsing

AFAIK, the Optionconstructor only takes two arguments, the text and the value. If you want to pass more data, I suggest you use the HTML5 data API:

AFAIK,Option构造函数只接受两个参数,文本和value. 如果你想传递更多的数据,我建议你使用 HTML5 数据 API:

var opt = new Option(concertArray[i][0], concertArray[i][1]);
opt.setAttribute('data-image', concertArray[i][2]);
select.options[select.options.length] = opt;

Then you can grab it using getAttribute('data-image')

然后你可以使用它来抓取它 getAttribute('data-image')

回答by Rupal

You can access values by using 2 for loops as below.

您可以使用 2 个 for 循环访问值,如下所示。

var concertArray = [
    ["Billy Joel", "99", "equal.png"],
    ["Bryan Adams", "89", "higher.png"],
    ["Brian Adams", "25", "lower.png"]
    ];

function populate(){
    for(i=0;i<arr.length;i++)
    {
        for(j=0;j<arr[i].length;j++)
        {
             console.log(arr[i][j]);
        }
    }
}