JavaScript 多维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2808926/
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
JavaScript Multidimensional Arrays
提问by JasonS
This wasn't the question I was going to ask but I have unexpectedly run aground with JavaScript arrays. I come from a PHP background and after looking at a few websites I am none the wiser.
这不是我要问的问题,但我意外地遇到了 JavaScript 数组。我来自 PHP 背景,在查看了一些网站后,我并不聪明。
I am trying to create a multi-dimensional array.
我正在尝试创建一个多维数组。
var photos = new Array;
var a = 0;
$("#photos img").each(function(i) {
photos[a]["url"] = this.src;
photos[a]["caption"] = this.alt;
photos[a]["background"] = this.css('background-color');
a++;
});
Error message: photos[a] is undefined. How do I do this? Thanks.
错误消息:photos[a] 未定义。我该怎么做呢?谢谢。
回答by Daniel Vassallo
JavaScript does not have multidimensional arrays, but arrays of arrays, which can be used in a similar way.
JavaScript 没有多维数组,而是数组的数组,可以以类似的方式使用。
You may want to try the following:
您可能想尝试以下操作:
var photos = [];
var a = 0;
$("#photos img").each(function(i) {
photos[a] = [];
photos[a]["url"] = this.src;
photos[a]["caption"] = this.alt;
photos[a]["background"] = this.css('background-color');
a++;
});
Note that you could have used new Array()instead of [], but the latter is generally recommended. Also note that you were missing the parenthesis of new Array()in the first line.
请注意,您可以使用new Array()代替[],但通常建议使用后者。另请注意,您缺少new Array()第一行中的括号。
UPDATE:Following from the comments below, in the above example there was no need to use arrays of arrays. An array of objects would have been more appropriate. The code is still valid because arrays are objects in this language, but the following would have been better:
更新:根据下面的评论,在上面的例子中,不需要使用数组数组。对象数组会更合适。该代码仍然有效,因为数组是这种语言中的对象,但以下内容会更好:
photos[a] = {};
photos[a]["url"] = this.src;
photos[a]["caption"] = this.alt;
photos[a]["background"] = this.css('background-color');
回答by Alsciende
You're trying to assign something to photos[a]["url"], photos[a]["caption"], etc., but photos[a]doesn't exist yet. photosis an empty Array at first, so you have to set photos[a]to something first. Since you want to use string keys ("url", "caption", etc), this something should be a plain object (the javascript equivalent to php associave arrays) (or a Hash if your code base allows it). Then you can use a literal object construct to simplify your function, and Array#pushto get rid of the unnecessary a:
你试图分配的东西photos[a]["url"],photos[a]["caption"]等等,但photos[a]还不存在。photos一开始是一个空数组,所以你必须先设置photos[a]一些东西。由于您想使用字符串键("url"、"caption"等),因此这应该是一个普通对象(相当于 php 关联数组的 javascript)(如果您的代码库允许,则为 Hash)。然后您可以使用文字对象构造来简化您的功能,并Array#push摆脱不必要的a:
var photos = [];
$("#photos img").each(function(img) {
photos.push({
url: img.src,
caption: img.alt,
background: img.style.backgroundColor
});
});
Also, make sure that thisis actually your imgelement. Some eachimplementations will set thisto the global object in your case.
另外,请确保这this实际上是您的img元素。在您的情况下,某些each实现将设置this为全局对象。
edit: ok, it looks like jQuery.eachautomatically sets thisto the iterated element, but doesn't wrap it in jQuery-goodness, so you have to either wrap thisin $()or use plain DOM (I used the latter in my example).
编辑:好吧,它看起来像jQuery.each自动设置this到迭代元素,但并没有把它包在jQuery的善良,所以你必须自动换行this中$()或使用纯DOM(我曾经在我的例子后者)。
edit2: anyway, using thisis kind of strange since the callback function passed to eachreceives an argument. Might as well use this argument (renamed).
edit2:无论如何, usingthis有点奇怪,因为传递给的回调函数each接收一个参数。不妨使用这个参数(重命名)。
回答by tau
var photos = [];
var imgs = document.getElementById("photos").getElementsByTagName("img");
for(var i=0;i<imgs.length;i++){
photos.push({
src:imgs[i].src,
alt:imgs[i].alt,
background:imgs[i].style.backgroundColor
});
}
That should give you something that is roughly equivalent to this in PHP (I made up pretend data):
这应该给你一些大致相当于 PHP 中的东西(我编造了假装数据):
Array(
[0] => Array(
"src" => "logo.png",
"alt" => "My Logo!",
"background" => "#ffffff"
)
)
I hope this helps!
我希望这有帮助!
回答by Paul Mason
When I read this thread I was trying to get an understanding of multidimensional associative arrays. It wasn't clear so I kept researching, this is what I came up with:
当我阅读此线程时,我试图了解多维关联数组。不清楚所以我一直在研究,这就是我想出的:
var images = new Array;
images['logo'] = { 'src': 'http://example.com/image1.png', 'caption': 'this is the logo', 'background': '#000'};
images['background'] = { 'src': 'http://example.com/image2.png', 'caption': 'this is the background', 'background': '#FFF'};
alert(images['logo']['src']); /* output: http://example.com/image1.png */
alert(images['background']['caption']); /* output: this is the background */
Hope this helps!
希望这可以帮助!
回答by Reigel
回答by GlenCrawford
Douglas Crockford, of JSLint, would have you create it this way ("Use the array literal notation []"):
JSLint 的Douglas Crockford会让您以这种方式创建它(“使用数组文字符号 []”):
var photos = [];
Now remember that you want to create multi-dimensional arrays, which means an array inside an array. This means you need to create the inner-arrays:
现在请记住,您要创建多维数组,这意味着数组中的数组。这意味着您需要创建内部数组:
$("#photos img").each(function(i) {
photos[a] = []
//continue

