-3

我如何在 javascript 中使用 document.write() 来访问这种形式的数组?

({"1":{"1":1,"2":1,"3":1},
  "2":{"1":1,"2":1,"3":2},
  "3":{"1":1,"2":2,"3":1},
  "4":{"1":1,"2":2,"3":2},
  "5":{"1":2,"2":1,"3":1,"4":1},
  "6":{"1":2,"2":1,"3":1,"4":2},
  "7":{"1":2,"2":1,"3":2},
  "8":{"1":2,"2":2,"3":1},
  "9":{"1":2,"2":2,"3":2}})
4

3 回答 3

1

例如,如果你想访问第一个数组的第一个元素,你应该写:

theData=({"1":{"1":1,"2":1,"3":1},
  "2":{"1":1,"2":1,"3":2},
  "3":{"1":1,"2":2,"3":1},
  "4":{"1":1,"2":2,"3":2},
  "5":{"1":2,"2":1,"3":1,"4":1},
  "6":{"1":2,"2":1,"3":1,"4":2},
  "7":{"1":2,"2":1,"3":2},
  "8":{"1":2,"2":2,"3":1},
  "9":{"1":2,"2":2,"3":2}});
document.write(theData[1][1]); //1

由于您显然使用了 jQuery,以下是打印元素的方法:

$(document).ready(function() { 
   $.getJSON('array.php?callback=?', function(data) {
     if(data) {
         $.each(data,function(key,val){
              $.each(val,function(subkey,subval){
                  document.write(subval+" ");
              });
              document.write('<br/>');
         });
     } 
     else { alert('error'); } 
   }); 

});

于 2012-11-25T12:21:55.110 回答
0

将其分配给变量并使用方括号表示法来访问对象属性。

var mydata = ({...});

mydata['1']['3'] //1
于 2012-11-25T12:21:32.257 回答
0

这不是一个数组,而是对象的对象。所以遍历每个对象并检查是否有嵌套对象。示例 旁注:表现出一些努力,更好的是,尝试多搜索一点,谷歌是你最好的朋友。

function traverse ( data )
{
    for ( var index in data )
    {
        if ( typeof data[index] === "object" )
        {
            traverse ( data[index] );
        } else {
            document.write ( data[index] );
        }
    }
    document.write ( "<br/>" );
}

traverse ( a );
于 2012-11-25T12:34:33.610 回答