jquery.each多维数组

时间:2010-08-24 14:58:15

标签: jquery

var array1 = {};

array1['one'] = new Array();
array1['one']['data'] = 'some text';
array1['one']['two'] = new Array();
array1['one']['two']['three'] = new Array();
array1['one']['two']['three']['data'] = 'some other text';

$.each(array1, function(key1, value1){
    $.each(value1['two']['three'], function(key1, value1){
        document.write('test');
    }
});

一切正常,除了它没有到达document.write。 任何人都知道为什么?

3 个答案:

答案 0 :(得分:11)

请注意,Array()替换是关键,缺少')'

var array1 = {};

array1['one'] = new Object();
array1['one']['data'] = 'some text';
array1['one']['two'] = new Object();
array1['one']['two']['three'] = new Object();
array1['one']['two']['three']['data'] = 'some other text';

$.each(array1, function(key1, value1) {
    $.each(value1['two']['three'], function(key1, value1) {
        document.write('test');
    });
});

和写同样的东西的另一种方法:(写入引用你的对象的小tweek)

var array1 = {};

array1.one = new Object();
array1.one.data = 'some text';
array1.one.two = new Object();
array1.one.two.three = new Object();
array1.one.two.three.data = 'some other text';


$.each(array1, function(key1, value1) {
    $.each(value1['two']['three'], function(key1, value1) {
        document.write('test' + array1.one.data);
    });
});

最后,使用已弃用的新Object()替换:

var array1 = {};

array1['one'] = {}
array1['one']['data'] = 'some text';
array1['one']['two'] = {};
array1['one']['two']['three'] = {};
array1['one']['two']['three']['data'] = 'some other text';

$.each(array1, function(key1, value1) {
    $.each(value1['two']['three'], function(key1, value1) {
        document.write('test');
    });
});

编辑:你的数组很有趣,为什么你可能会在对象声明中拥有字符串:

var array1 = {}; 
var fun="four"; 
array1.one = {}; 
array1.one.data = 'some text'; 
array1.one.two = {}; 
array1.one.two.three = {}; 
array1.one.two.three.data = 'some other text'; 
array1.one.two[fun] = {};
array1.one.two[fun].data=' howdy';

$.each(array1, function(key1, value1) { 
    $.each(value1.two.three, function(key1, value1) { 
        document.write('test'+array1.one.two[fun].data+ ":"+key1+":"+value1); 
    }); 
});

输出最后一个是:“测试你好:数据:其他一些文字”

答案 1 :(得分:1)

document.write没有工作,因为你有一个语法错误,所以代码流永远不会到达它 - 你需要在each末尾的另一个括号,即

$.each(array1, function(key1, value1){
    $.each(value1['two']['three'], function(key1, value1){
        document.write('test');
    })
});

如果您要使用javascript进行任何非平凡的工作,我强烈建议您使用安装了Firebug的Firefox - 它的控制台会突出显示这些错误,否则如果您没有意识到这些错误就会失败,让你相信一切正常。

答案 2 :(得分:1)

您在第二个)中错过each