Is it possible to create an empty multidimensional array in javascript/jquery?

后端 未结 8 2204
粉色の甜心
粉色の甜心 2020-12-06 10:36

I am trying to create a very basic Flickr gallery using the Flickr API. What I want to achieve is sorting my pictures by tag. What I am using is jQuery.getJSON() so that I c

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 11:26

    JavaScript doesn't have true multidimensional arrays (heck, it doesn't even have true regular arrays...), but, like most languages, it instead uses arrays of arrays. However, to me it looks like you need an object (kinda similar to PHP's arrays) containing arrays.

    var data = {
        tag1: ['URL_1', 'URL_2', 'URL_3', 'URL_n']
    };
    // Then accessed like:
    data.tag1; // ['URL_1', ...]
    data.tag1[0]; // 'URL_1'
    data.tag1[1]; // 'URL_2'
    // etc.
    

    So, you're problem would look something like this:

    var tags = {};
    $.each(data.photoset.photo, function (i, item) {
        $.each(item.tags.split(" "), function (i, tag) {
            if (!tags[tag])
                tags[tag] = [];
            tags[tag].push(item.url_sq);
        });
    });
    // tags is now something like:
    // {
        "foo": ["/url.html", "/other-url/", ...],
        "bar": ["/yes-im-a-lisp-programmer-and-thats-why-i-hypenate-things-that-others-might-underscore-or-camelcase/", ...],
        ...
    //}
    

提交回复
热议问题