gpt4 book ai didi

javascript - 如果在保存的数组中找不到结果,则发出警报

转载 作者:行者123 更新时间:2023-12-01 03:22:08 24 4
gpt4 key购买 nike

我从第一次加载的 api 中获取数据并将其保存在数组中。然后,当用户指定他/她想要搜索的日期范围时,我根据用户指定的内容将结果从保存的数组显示到 View 中。它工作完美,但问题是当用户搜索没有结果时我能够显示错误消息

.controller('billing_statement_ctrl', function($scope, $http, $ionicLoading, $ionicPopup, $cordovaToast, $location, $ionicModal, $filter) {
$scope.account_number = localStorage.getItem("account_number");
///alert if connection fails
$scope.connect = function() {
var alertPopup = $ionicPopup.alert({
title: 'Error',
template: '<p align="center">Problem Contacting Server</p>',
});
};

$scope.state_request = function() {
$http.post("http://localhost/server/statement.php", {
'id': $scope.account_number
}).success(function(data) {
console.log(JSON.stringify(data));
$scope.record = data;
})

$scope.from = $filter('date')($scope.sdate, "yyyy-MM-dd" + 'T00:00:00') + 'Z';
$scope.to = $filter('date')($scope.edate, "yyyy-MM-dd" + 'T00:00:00') + 'Z';


}

})

.filter('dateRange', function() {
return function(records, from, to) {
return records.filter(function(record) {
return record.Date >= from && record.Date <= to;
if (record == '') {
alert('its empty')
} else {
alert('results found')
}
});
}
})

当我的脚本成功或不成功时,我不会发出警报。

其次,当页面加载时,我收到此错误无法读取未定义的属性“filter”

最佳答案

您不会收到警报,因为在触发警报的条件之前有一个 return

函数中return之后的代码不会执行。也不要使用 alert() 进行调试...使用 console 方法,例如 console.log()

对于初始加载,过滤器正在未定义的输入值上运行,可能是因为 View 中的变量在 http 请求完成之前才定义。因此它还不是一个数组,并且错误告诉您不能对其使用数组方法

如果输入未定义,则调整自定义 Angular 过滤器以返回 null 或空数组。

.filter('dateRange', function() {
return function(records, from, to) {
// return empty array if input not defined or not array
if(!records || !angular.isArray(records)){
return [];
}
var results = records.filter(function(record) {
// run console log tests here...before the return
return record.Date >= from && record.Date <= to;
});
console.log( 'Number of results:', results.length);
return results;
}
})

关于javascript - 如果在保存的数组中找不到结果,则发出警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45119527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com