JavaScript 多维数组

标签 javascript jquery arrays

<分区>

这不是我要问的问题,但我意外地遇到了 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');

关于JavaScript 多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2808926/

相关文章:

javascript - 拖动时出现意外的边距/填充 (jQuery Ui)

javascript - LABjs : How to append the scripts to the end of the body tag

C# MVC 模型在发布时绑定(bind)到索引数组

php - 我有一个 SQL 表。对于 PHP 的 SQL 请求,我想将该请求的结果存储在变量中。

javascript - 调用 javascript 函数后进行下载

javascript - 单击 span 时关注 span 内的第一个表单元素

javascript - Bootstrap 网格中的偶数列

javascript - 使用 JQuery 提交简单表单并对必填字段进行限制?

javascript - 从元素的文本中获取整数

c - 在 C 中通过引用传递数组