简体   繁体   中英

How do I output an element from an array in a javascript for loop?

DEMO: http://jsfiddle.net/gc9S3/10/

For each row in the array, I want the "for" loop to output a [i] element. For example, I want the javascript below to spit out the following in the UI:

1 2 3

(each of the numbers, of course, will be wrapped in a div tag.)

However, as you can see from the JSFiddle demo, only the element from the last element in the array is being spit out! Is there something wrong with my "for" loop?

var myArray = [
  ['stringa', 'stringb', 'stringc', 1],
  ['stringd', 'stringe', 'stringf', 2],    
  ['stringg', 'stringh', 'stringi', 3]
];

for (var i=0; i< myArray.length; i++) {
$('#container').html('<div class="hidden caption' + i + '">' + myArray[i][3] + '</div>');
}

<div id="container"></div>

您在每次迭代中替换所有内容,需要添加新元素。

$('#container').append('<div class="hidden caption' + i + '">' + myArray[i][3] + '</div>');

Your issue is html v/s append . But you can try this way. Instead of making multiple DOM operation on each iteration do it at the end, which will definitely perform better especially when you have lot many items in your array.

var myArray = [
      ['stringa', 'stringb', 'stringc', 1],
      ['stringd', 'stringe', 'stringf', 2],    
      ['stringg', 'stringh', 'stringi', 3]
    ];

var $els = $.map(myArray, function(val, i){ //Convert one collection collection to another using map
  return '<div class="hidden caption' + i + '">' + val[3] + '</div>';
});

$('#container').html($els); //append it at the end.

Demo

As @epascarello mentioned you are overwriting the html with each iteration.

Also, you should try avoid making changes to the DOM where possible. In this case store the markup in a variable and update the DOM after the for loop. Solves your problem, plus only 1 DOM change.

var html = '';
for (var i=0; i< myArray.length; i++) {
    html += '<div class="hidden caption' + i + '">' + myArray[i][3] + '</div>';
}
$('#container').html(html);

Updated JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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