JavaScript多维数组

这不是我要问的问题,但我出乎意料地使用JavaScript数组搁浅了。 我来自PHP背景,在查看几个网站后,我不是更明智的。

我正在尝试创建一个多维数组。

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++; }); 

错误消息:照片[a]未定义。 我该怎么做呢? 谢谢。

JavaScript没有多维数组,但是数组数组可以以类似的方式使用。

您可能想尝试以下操作:

 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++; }); 

请注意,您可以使用new Array()而不是[] ,但通常建议使用后者。 另请注意,您在第一行中缺少new Array()的括号。


更新:根据以下注释,在上面的示例中,不需要使用数组数组。 一组对象本来更合适。 代码仍然有效,因为数组是这种语言的对象,但以下情况会更好:

 photos[a] = {}; photos[a]["url"] = this.src; photos[a]["caption"] = this.alt; photos[a]["background"] = this.css('background-color'); 

你正在尝试为photos[a]["url"]photos[a]["caption"]等分配内容,但photos[a]尚不存在。 photos是一个空数组,所以你必须先将photos[a]设置为某个东西。 由于你想使用字符串键( "url""caption"等),这个东西应该是一个普通的对象(javascript等同于php associave数组)(或者如果你的代码库允许的话,就是哈希)。 然后你可以使用文字对象构造来简化你的function,并且使用Array#push来摆脱不必要的a

 var photos = []; $("#photos img").each(function(img) { photos.push({ url: img.src, caption: img.alt, background: img.style.backgroundColor }); }); 

另外,请确保this实际上是您的img元素。 有些实现会this设置为您的案例中的全局对象。

编辑:好吧,看起来jQuery.each自动将它设置为迭代元素,但不会将其包装在jQuery-goodness中,所以你必须将它包装在$()或使用纯DOM(我使用后者)我的例子)。

edit2:无论如何,使用this有点奇怪,因为传递给each的回调函数接收一个参数。 不妨使用这个参数(重命名)。

 var photos = []; var imgs = document.getElementById("photos").getElementsByTagName("img"); for(var i=0;i 

这应该会给你一些与PHP大致相同的东西(我编写假装数据):

 Array( [0] => Array( "src" => "logo.png", "alt" => "My Logo!", "background" => "#ffffff" ) ) 

我希望这有帮助!

当我读到这个post时,我试图理解多维关联数组。 目前尚不清楚,所以我一直在研究,这就是我提出的:

 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 */ 

希望这可以帮助!

多维数组在这些结构中:

 var photos = new Array(); photos[0] = new Array(); 

用它作为:

 photos[0][0] = this.src; 

更多关于JS数组的信息 。

JSLint的 Douglas Crockford会让你以这种方式创建它(“ 使用数组文字符号[] ”):

 var photos = []; 

现在请记住,您要创建多维数组,这意味着数组中的数组。 这意味着您需要创建内部数组:

 $("#photos img").each(function(i) { photos[a] = [] //continue