是否可以在 javascript/jquery 中创建一个空的多维数组?

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

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

javascriptjqueryarraysmultidimensional-arrayflickr

提问by finferflu

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 can parse the API response of flickr.photosets.getPhotos.

我正在尝试使用 Flickr API 创建一个非常基本的 Flickr 画廊。我想要实现的是按标签对我的图片进行排序。我使用的是 jQuery.getJSON() 以便我可以解析flickr.photosets.getPhotos的 API 响应。

The data I am interested in getting from Flickr is the tag and the URL associated to each photo. The problem with this is that the only logical way out of this for me is creating a multidimensional array of the following format:

我有兴趣从 Flickr 获取的数据是与每张照片关联的标签和 URL。问题在于,对我来说,唯一合乎逻辑的方法是创建以下格式的多维数组:

Array['tag1'] => ['URL_1', 'URL_2', 'URL_3', 'URL_n'];

However, I cannot find any way to achieve this. My code looks like this:

但是,我找不到任何方法来实现这一目标。我的代码如下所示:

$.getJSON('http://api.flickr.com/services/rest/?api_key=xxx&method=flickr.photosets.getPhotos&user_id=xxx&format=json&extras=tags%2C+url_l%2C+url_sq&nojsoncallback=1&photoset_id=xxx', 
   function(data) {

     var imageArray = [];   
     $.each(data.photoset.photo, function(i, item) {

       imageArray[item.tags] = [item.url_sq,];

     });
});

I am aware that the code might look awkward, but I've tried everything and there's no way I can figure this out.

我知道代码可能看起来很笨拙,但我已经尝试了所有方法,但我无法弄清楚这一点。

回答by Raynos

var arr = [];
arr[0] = [];
arr[0][0] = [];
arr[0][0][0] = "3 dimentional array"

Multi dimentional arrays have a lot of gaps unless they are used properly. A two dimensional array is called a matrix.

除非使用得当,否则多维数组会有很多差距。二维数组称为矩阵。

I believe your data contains a space seperate string called "tags" containing the tags and a single url.

我相信您的数据包含一个名为“标签”的空格分隔字符串,其中包含标签和一个 url。

var tagObject = {};
data.photoset.photo.forEach(function(val) {
  val.tags.split(" ").forEach(function(tag) {
    if (!tagObject[tag]) {
      tagObject[tag] = [];
    }
    tagObject[tag].push(val.url_sq);
  });
});
console.log(tagObject); 
/*
  {
    "sea": ["url1", "url2", ...],
    "things": ["url4", ...],
    ...
  }
*/

I don't know how it returns multiple tags.

我不知道它如何返回多个标签。

回答by Pimp Trizkit

Yes it is! I found this to be quite fast. I might stretch to say that it could be the fastest way possible to generate a N Dimensional array of Ns lengths resulting in empty arrays using JavaScript. (i.e. an arbitrary number of dimensions each with an arbitrary length)

是的!我发现这非常快。我可能会说这可能是使用 JavaScript 生成 Ns 长度的 N 维数组的最快方法,从而导致空数组。(即任意数量的维度,每个维度都具有任意长度)

Even though the definition of an array in JavaScript is foggy at best.

尽管 JavaScript 中数组的定义充其量是模糊的。

function createNDimArray(dimensions) {
    var t, i = 0, s = dimensions[0], arr = new Array(s);
    if ( dimensions.length < 3 ) for ( t = dimensions[1] ; i < s ; ) arr[i++] = new Array(t);
    else for ( t = dimensions.slice(1) ; i < s ; ) arr[i++] = createNDimArray(t);
    return arr;
}

Usages:

用法:

var arr = createNDimArray([3, 2, 3]); 
//  arr = [[[,,],[,,]],[[,,],[,,]],[[,,],[,,]]]
console.log(arr[2][1]); // in FF: Array [ <3 empty slots> ]
console.log("Falsy = " + (arr[2][1][0]?true:false) ); // Falsy = false

If you care to read more; check my answerto this question.

如果您想阅读更多;检查我的回答这个问题

回答by Joseph Marikle

I think the syntax you are attempting to achieve is something like the following:

我认为您尝试实现的语法如下所示:

var item = {"tags":"blah","url_sq":"example.com"}; // for sake of example.
var imageArray = [];
$.each(data.photoset.photo, function(i, item) {
   imageArray.push({"tags":item.tags,"url":item.url_sq});
});

and then reference it like this:

然后像这样引用它:

imageArray[0].tags
imageArray[0].url
imageArray[1].tags
imageArray[1].url
...

回答by Peter C

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.

JavaScript 没有真正的多维数组(见鬼,它甚至没有真正的常规数组……),但是,像大多数语言一样,它使用数组的数组。但是,在我看来,您需要一个包含数组的对象(有点类似于 PHP 的数组)。

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/", ...],
    ...
//}

回答by Nettogrof

Maybe something like that in your each:

也许你的each

if ( imageArray[item.tags] != null ){
   imageArray[item.tags][imageArray[item.tags].length] = item.url_sq;
}else{
   imageArray[item.tags] = [];
}

回答by Billy Moon

I think something like this should do what you want

我认为这样的事情应该做你想做的

 var imageArray = [];   

 $.each(data.photoset.photo, function(i, item) {

   // if the tag is new, then create an array
   if(!imageArray[item.tags])
     imageArray[item.tags] = [];

   // push the item url onto the tag
   imageArray[item.tags].push(item.url_sq);

 });

回答by MUSTAPHA GHLISSI

You can simply try this one for 2d js array:

您可以简单地为 2d js 数组尝试这个:

let myArray = [[]];

回答by Maksim Shamihulau

Yes, it's possible to have multidimensional arrays in javascript.

是的,在 javascript 中可以有多维数组。

Here are one-liners for 5x5 matrix:

以下是 5x5 矩阵的单行:

Array(5).fill(0).map(() => new Array(5).fill(0))

Array(5).fill(0).map(() => new Array(5).fill(0))

Or

或者

[...Array(5)].map(x=>Array(5).fill(0))

[...Array(5)].map(x=>Array(5).fill(0))