简体   繁体   English

迭代嵌套有对象键的数组

[英]Iterating an array that is nested with an object key

var html = {
easyBB :   
['easybbtutorials','www.easybbtutorials.com','http://i76.servimg.com/u/f76/17/83/35/07/easybb10.png'],
AvacWeb:
['AvacWeb','www.avacweb.com','http://i45.servimg.com/u/f45/16/35/08/55/new_lo12.png'],
easyBB2:
['easybbtutorials','www.easybbtutorials.com','http://i76.servimg.com/u/f76/17/83/35/07/easybb10.png'],
AvacWeb2 : 
['AvacWeb','www.avacweb.com','http://i45.servimg.com/u/f45/16/35/08/55/new_lo12.png'],
easyBB3 :
['easybbtutorials','www.easybbtutorials.com','http://i76.servimg.com/u/f76/17/83/35/07/easybb10.png'],
AvacWeb3 : 
['AvacWeb','www.avacweb.com','http://i45.servimg.com/u/f45/16/35/08/55/new_lo12.png']
};
 var cont = document.getElementById('container');
  for(var key in html){
   for(var i =0;i<key.length;i++ ){
     var name= '<span class="name">'+html[key][0] +'</span>',
     link = '<span class="url"><a href="'+html[key][1]+'">'+html[key][1] +'</a></span>',
     image = '<img src="'+html[key][2]+'" title="'+html[key][0]+'" />';        
     cont.innerHTML= '<div class="wrapper">'+ name + '<br />'+image+'<br />'+link+'</div>';
      i++;
   }
 }

I am trying to iterate over the arrays in each key of the HTML object I created problem is not sure how to do this I've tried multiple ways now and I believe (since I am posting) I am doing this all wrong. 我试图遍历我创建的HTML对象的每个键中的数组,问题是不确定如何做到这一点。我现在已经尝试了多种方法,并且我相信(因为我正在发布)我做错了所有这些。 I've also tried doing: html[key[i]][0] though of course I get an error of i is not defined. 我也尝试过: html[key[i]][0]尽管我得到的错误是我没有定义。 Any suggestions what I am doing wrong, as of right now it is only posting one array to the html. 任何建议,我在做什么错,截至目前,它只是将一个数组发布到html。

The problem is not the iteration, it's the line 问题不是迭代,而是线

cont.innerHTML = ...

which is replacing the content each time the loop iterates so that you only see the final item ("AvacWeb3"). 每次循环迭代时,它都会替换内容,因此您只能看到最终项目(“ AvacWeb3”)。

Change that to 更改为

cont.innerHTML += ...

and get rid of the for (var i =0 ... loop which isn't needed. ( jsfiddle ) 并摆脱for (var i =0 ...不需要的循环。( jsfiddle

for(var i = 0; i < html[key].length; i++){
...

You should do html[key][i][0]. 您应该执行html [key] [i] [0]。
And also you should do what Trevor said, html[key].length instead of key.length. 而且,您还应该执行Trevor所说的html [key] .length而不是key.length。

Make yourself easy by assigning html[key] to var currentkey for example, easier to keep track on. 例如,通过将html [key]分配给var currentkey来使自己更轻松,更容易跟踪。

Also, look into array.forEach, just for fun ;) 另外,看看array.forEach,只是为了好玩;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM