JavaScript 中的多维关联数组 [英] Multi-dimensional associative arrays in JavaScript

查看:27
本文介绍了JavaScript 中的多维关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查询结果如下:(key1和key2可以是任意文本)

There is the following query results: (key1 and key2 could be any text)

id   key1     key2     value

1    fred     apple    2
2    mary     orange   10
3    fred     banana   7
4    fred     orange   4
5    sarah    melon    5
...

并且我希望将数据存储在网格中(可能作为数组)循环所有记录如下:

and I wish to store the data in a grid (maybe as an array) looping all the records like this:

         apple    orange   banana  melon
fred        2        4         7     -
mary        -        10        -     -
sarah       -        -         -     5

在 PHP 中这会很容易,使用关联数组:

In PHP this would be really easy, using associative arrays:

$result['fred']['apple'] = 2;

但是在 JavaScript 中,像这样的关联数组不起作用.在阅读了大量教程后,我所能得到的就是:

But in JavaScript associative arrays like this doesn't work. After reading tons of tutorial, all I could get was this:

arr=[];
arr[1]['apple'] = 2;

但是 arr['fred']['apple'] = 2; 不起作用.我尝试了对象数组,但对象属性不能是自由文本.我看教程越多,我就越糊涂...

but arr['fred']['apple'] = 2; doesn't work. I tried arrays of objects, but objects properties can't be free text. The more I was reading tutorials, the more I got confused...

欢迎任何想法:)

推荐答案

只需使用常规 JavaScript 对象,它会以与关联数组相同的方式读取".您还必须记住先初始化它们.

Just use a regular JavaScript object, which would 'read' the same way as your associative arrays. You have to remember to initialize them first as well.

var obj = {};

obj['fred'] = {};
if('fred' in obj ){ } // can check for the presence of 'fred'
if(obj.fred) { } // also checks for presence of 'fred'
if(obj['fred']) { } // also checks for presence of 'fred'

// The following statements would all work
obj['fred']['apples'] = 1;
obj.fred.apples = 1;
obj['fred'].apples = 1;

// or build or initialize the structure outright
var obj = { fred: { apples: 1, oranges: 2 }, alice: { lemons: 1 } };

如果您正在查看值,您可能会看到如下所示的内容:

If you're looking over values, you might have something that looks like this:

var people = ['fred', 'alice'];
var fruit = ['apples', 'lemons'];

var grid = {};
for(var i = 0; i < people.length; i++){
    var name = people[i];
    if(name in grid == false){
        grid[name] = {}; // must initialize the sub-object, otherwise will get 'undefined' errors
    }

    for(var j = 0; j < fruit.length; j++){
        var fruitName = fruit[j];
        grid[name][fruitName] = 0;
    }
}

这篇关于JavaScript 中的多维关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆