JavaScript的多维数组 [英] JavaScript Multidimensional Arrays

查看:91
本文介绍了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++;
});

错误信息:照片[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++;
});

请注意,您也可以使用新的Array()而不是 [] ,但后者通常建议。另外请注意,你失踪的括号新的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.

更新:从下面的评论之后,在上面的例子中,没有必要使用数组的数组。对象的数组将是更合适的。在code仍然是有效的,因为数组是在这个语言对象,但下面会更好:

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天全站免登陆