使用3个JavaScript数组

时间:2018-06-05 09:53:31

标签: javascript jquery html

我是JavaScript的初学者。我在下面有一个jQuery函数,它允许我用2个数组red,blue填充HTML表,但是我很难在函数中添加另一个数组green。是否可以只添加另一个数组或者我必须以另一种方式执行此操作?

var red = ["apple", "cherry", "tomato"];
var blue = ["blueberry", "sky"]
var green = ["cabbage", "broccoli", "plants"]

var bodyString = '';
$.each(blue, function(index, blu) {
  bodyString += ('<tr><td>' + blu + '</td><td>' + red[index] + '</td></tr>');
});
$('.countriesTable tbody').html(bodyString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="countriesTable">
  <thead>
    <tr>
      <th>Country</th>
      <th>Capital</th>
  </thead>
  <tbody></tbody>
  </table>

2 个答案:

答案 0 :(得分:0)

&#13;
&#13;
var red = ["apple", "cherry", "tomato"];
var blue = ["blueberry", "sky"]
var green = ["cabbage", "broccoli", "plants"]

var bodyString = '';
$.each(blue, function(index, blu) {
  bodyString += ('<tr><td>' + blu + '</td><td>' + red[index] + '</td> +<td>' + green[index] + '</td></tr>');
});
$('.countriesTable tbody').html(bodyString);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="countriesTable">
  <thead>
    <tr>
      <th>Country</th>
      <th>Capital</th>
  </thead>
  <tbody></tbody>
  </table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这可能是你想要做的事情 - 我添加了答案,因为做你想做的事并不简单。

改进可以在一次通过中执行此操作,并可能使用.map作为数组

&#13;
&#13;
var colours = {
  "red": ["apple", "cherry", "tomato"],
  "blue": ["blueberry", "sky"],
  "green": ["cabbage", "broccoli", "plants"]
}

var $header = $("<tr>"),
  cols = 0,
  bodyString = "";

$.each(colours, function(key, values) {
  $header.append($('<th/>').text(key));
  cols = Math.max(cols, values.length); // find the longest
});
for (var i = 0; i < cols; i++) { // or use .map, but this is more undertandable for beginners
  bodyString += '<tr>';
  $.each(colours, function(key, values) {
    bodyString += '<td>' + 
      (values[i] ? values[i] : "-") + // ternary - instead of using if/else
      '</td>';
  });
  bodyString += '</tr>';
}
$('.fruitAndVegTable thead').html($header);
$('.fruitAndVegTable tbody').html(bodyString);
&#13;
th,
td {
  border: 1px solid black
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="fruitAndVegTable">
  <thead></thead>
  <tbody></tbody>
</table>
&#13;
&#13;
&#13;