离子警报 - 检查结果是否未定义

Ionic alert - check if result is undefined

本文关键字:结果 结果是 是否 未定义 检查      更新时间:2023-09-26

我从带有angular和Ionic的服务器加载一个JSON文件。

这是我的代码:

$scope.showAlert = function(mo,di,mi,don,fr,sa,so) {
              $ionicPopup.alert({
                title: 'Success',
                content: mo + "<br>" + di + "<br>" + mi + "<br>" + don + "<br>" + fr + "<br>" + sa+ "<br>" + so
              }).then(function(res) {
                console.log('Test Alert Box');
              });
            };

对于项目:

<i class="icon ion-ios-clock-outline links" ng-click="showAlert(item.openingHours[0], item.openingHours[1], item.openingHours[2], item.openingHours[3],
  item.openingHours[4], item.openingHours[5], item.openingHours[6]
)"></i>

我的问题是有时结果,例如item.openHours[6]是未定义的。我不希望警报中包含未定义的文本。如何检查警报中是否未定义值?

使用条件(三元)运算符 ? ,检查是否定义了str,如果已定义,则返回带有 br 的值,如果不是 - 空字符串:

$scope.showAlert = function(mo, di, mi, don, fr, sa, so) {
  function getStrWithBr(str) {
    return str ? str + '<br/>' : '';
  }
  var content = 
    getStrWithBr(mo) +
    getStrWithBr(di) + 
    getStrWithBr(mi) + 
    getStrWithBr(fr) + 
    getStrWithBr(sa) + 
    so || '';
 ...