Jas*_*onS 26 javascript arrays jquery
这不是我要问的问题,但我出乎意料地使用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++;
});
Run Code Online (Sandbox Code Playgroud)
错误消息:照片[a]未定义.我该怎么做呢?谢谢.
Dan*_*llo 34
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++;
});
Run Code Online (Sandbox Code Playgroud)
请注意,您可以使用new Array()而不是[],但通常建议使用后者.另请注意,您缺少new Array()第一行的括号.
更新:根据以下注释,在上面的示例中,不需要使用数组数组.一组对象本来更合适.代码仍然有效,因为数组是这种语言的对象,但以下情况会更好:
photos[a] = {};
photos[a]["url"] = this.src;
photos[a]["caption"] = this.alt;
photos[a]["background"] = this.css('background-color');
Run Code Online (Sandbox Code Playgroud)
Als*_*nde 16
你试图分配的东西photos[a]["url"],photos[a]["caption"]等等,但photos[a]还不存在.photos最初是一个空数组,所以你必须先设置photos[a]一些东西.由于你想使用字符串键("url","caption"等),这个东西应该是一个普通的对象(javascript等同于php associave数组)(或者如果你的代码库允许的话,就是哈希).然后你可以使用文字对象构造来简化你的功能,并Array#push摆脱不必要的a:
var photos = [];
$("#photos img").each(function(img) {
photos.push({
url: img.src,
caption: img.alt,
background: img.style.backgroundColor
});
});
Run Code Online (Sandbox Code Playgroud)
另外,请确保它this实际上是您的img元素.在您的情况下,某些each实现将设置this为全局对象.
编辑:好吧,它看起来像jQuery.each自动设置this的迭代的元素,但在jQuery的善良不换行,所以你必须要么包裹this在$()或使用纯DOM(我用的是后者在我的例子).
edit2:无论如何,使用this有点奇怪,因为传递回调函数each接收一个参数.不妨使用这个参数(重命名).
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
});
}
Run Code Online (Sandbox Code Playgroud)
这应该会给你一些与PHP大致相同的东西(我编写假装数据):
Array(
[0] => Array(
"src" => "logo.png",
"alt" => "My Logo!",
"background" => "#ffffff"
)
)
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助!
| 归档时间: |
|
| 查看次数: |
57347 次 |
| 最近记录: |