JavaScript 多维数组 [英] JavaScript Multidimensional Arrays

查看:27
本文介绍了JavaScript 多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是我要问的问题,但我意外地遇到了 JavaScript 数组.我来自 PHP 背景,在浏览了一些网站后,我并不明智.

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.

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

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

错误消息:photos[a] 未定义.我该怎么做呢?谢谢.

Error message: photos[a] is undefined. How do I do this? Thanks.

推荐答案

JavaScript 没有多维数组,而是数组的数组,可以用类似的方法.

JavaScript does not have multidimensional arrays, but arrays of arrays, which can be used in a similar way.

您可能想尝试以下操作:

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

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

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.

更新: 根据下面的评论,在上面的示例中,不需要使用数组数组.对象数组会更合适.该代码仍然有效,因为数组是这种语言中的对象,但以下内容会更好:

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');

这篇关于JavaScript 多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆