Table 来自数组,隐藏空行

Table from array, hide empty rows

对于 Google 地图,我尝试用数组填充信息 window。 如果数组中不存在某个值,则不应显示整行。

例如:如果数组中没有电子邮件,则根本不应显示行 "Email:"。我试图用以下代码解决这个问题:

但是,我是 Javascript 的完全初学者,不幸的是它不起作用。

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 'City' , 'Country', '+39 0584 430461', 'info@centronauticocom.com', 'www.centronauticocom.com'],
  ['Coogee Beach', -33.923036, 151.259052],
];

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent
    
    ('<div class="inside">' + '<span>' + locations[i][0] +'</span>' + locations[i][3] + ' • ' + locations[i][4] + '<table><tbody>' + 
 if (locations[i][5] !== null) { '<tr><td width="60">Tel.:</td><td><a href="tel:' + locations[i][5] + '">' + locations[i][5] + '</a></td></tr>'} + 
 if (locations[i][6] !== null) { '<tr><td width="60">Email:</td><td><a href="mailto:' + locations[i][6] + '">' + locations[i][6] + '</a></td></tr>' } + 
  if (locations[i][7] !== null) { '<tr><td width="60">Web:</td><td><a href="http://' + locations[i][7] + '" target="_blank">' + locations[i][7] + '</a></td></tr>' } + '</tbody></table>' + '</div>'  
               
               );
      infowindow.open(map, marker);
    }
  })(marker, i));
}

您可以使用ternary operator, but in this case i believe it's better to separate in if statements. I'm also using template literals使代码更清晰。

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 'City', 'Country', '+39 0584 430461', 'info@centronauticocom.com', 'www.centronauticocom.com'],
  ['Coogee Beach', -33.923036, 151.259052]
];

function getDescription(i) {
  var result = `<div class="inside">
    <span>${locations[i][0]}</span>
    ${locations[i][1]} • ${locations[i][2]}<table><tbody>`;
  if (locations[i][5]) result += `<tr><td width="60">Tel.:</td>
    <td><a href="tel:${locations[i][5]}">${locations[i][5]}</a></td></tr>`;
  if (locations[i][6]) result += `<tr><td width="60">Email:</td>
    <td><a href="mailto:${locations[i][6]}">${locations[i][6]}</a></td></tr>`;
  if (locations[i][7]) result += `<tr><td width="60">Web:</td>
    <td><a href="http://${locations[i][7]}" target="_blank">
    ${locations[i][7]}</a></td></tr>`
  result += `</tbody></table></div>`;
  return result;
}

console.log(getDescription(0));
console.log(getDescription(1));