如何打印多个阵列的结果?

时间:2016-05-10 14:07:58

标签: javascript jquery arrays each

我在从每个数组索引按顺序打印多个数组值时遇到问题。我有三个数组,我只想迭代一次。假设在$.each()的选择器参数中定义了三个数组,$.each()函数将遍历整个数组三次。这是jsfiddle中的代码和输出。

var _videoIdArr = ["via1","via2", "via3", "via4", "via5"];
var _vidTitleArr = ["t1", "t2", "t3", "t4", "t5"]; 
var _viewCountArr = ["v1", "v2", "v3", "v4", "v5"]; 

// loop thru multiple arrays and print total values
$.each([_videoIdArr, _vidTitleArr, _viewCountArr], function()
{
   $.each(this, function(i, item)
   {
      // construct the div
      vidThumbnail = '<div class="video">ID: ' + _videoIdArr[i] + '<br/>Title: ' + _vidTitleArr[i] + '<br/>Count: ' + _viewCountArr[i] + '</div>';
     console.log(vidThumbnail);

     // print the div
     $('.section.video > .thumb').append(vidThumbnail);
    });
});

3 个答案:

答案 0 :(得分:0)

使用经典for循环怎么样?假设有三个数组的长度与看起来应该相同:

for (var i = 0; i < _videoIdArr.length; i++) {
  vidThumbnail = '<div class="video">ID: ' + _videoIdArr[i] + '<br/>Title: ' + _vidTitleArr[i] + '<br/>Count: ' + _viewCountArr[i] + '</div>';
  console.log(vidThumbnail);

  // print the div
  $('.section.video > .thumb').append(vidThumbnail);
}

或者如果你想使用$.each,你可以使用索引变量:

$.each(_videoIdArr, function(i) {
  vidThumbnail = '<div class="video">ID: ' + _videoIdArr[i] + '<br/>Title: ' + _vidTitleArr[i] + '<br/>Count: ' + _viewCountArr[i] + '</div>';
  console.log(vidThumbnail);

  // print the div
  $('.section.video > .thumb').append(vidThumbnail);
});

答案 1 :(得分:0)

假设所有数组都具有相同的长度且没有丢失的属性,则只需要一个each循环:

var _videoIdArr = ["via1", "via2", "via3", "via4", "via5"];
var _vidTitleArr = ["t1", "t2", "t3", "t4", "t5"];
var _viewCountArr = ["v1", "v2", "v3", "v4", "v5"];

// loop thru multiple arrays and print total values

$.each(_videoIdArr, function(i, item) {
  // construct the div
  vidThumbnail = '<div class="video">ID: ' + _videoIdArr[i] + '<br/>Title: ' + _vidTitleArr[i] + '<br/>Count: ' + _viewCountArr[i] + '</div>';
  console.log(vidThumbnail);

  // print the div
  $('body').append(vidThumbnail);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 2 :(得分:0)

您可以使用Array.concat() ,。apply()`将所有数组合并为单个数组

$.each([].concat.apply([], [_videoIdArr, _vidTitleArr, _viewCountArr])
, function(i, item) {
  // construct the div
  var vidThumbnail = '<div class="video">ID: ' 
                     + item + '<br/>Title: ' 
                     + item + '<br/>Count: ' 
                     + item + '</div>';
  console.log(vidThumbnail);

  // print the div
  $('.section.video > .thumb').append(vidThumbnail);
});

jsfiddle https://jsfiddle.net/jnksv4zp/1/