我使用javascript的排序函数在角范围内的一个if条件.我的条件是假的,但它还是要进去

I am using javascript sort function on angular scope inside an if condition. My condition is false still it is going inside

本文关键字:条件 我的 if 一个 排序 函数 javascript 范围内      更新时间:2023-09-26

代码片段如下:

$scope.notes = notes.data;
if($scope.notes) {
   console.log("notes", $scope.notes);
} else {
   console.log("no notes");
}
if($scope.notes) {
  console.log("in this if");
  $scope.singleNote = $scope.notes.sort(function(a,b) { 
     return new Date(b.date_posted).getTime() - new Date(a.date_posted).getTime()
  })[0];
}

即使逻辑进入else,它也会进入第二个if。它不显示第二个if的控制台,但给出一个名为:$scope.notes的错误。函数未定义。它不应该出现在第二个if中,如果它出现在else块中

您面临的问题是因为您声明在$scope上使用数组函数sort而发生的。注意在代码被解释的时候可能不是一个数组。而不是检查$scope。Notes控制$作用域。数据已定义

$scope.notes = [];
if(notes.data) {
   $scope.notes = notes.data;
   console.log("notes", $scope.notes);
} else {
   console.log("no notes");
}
if($scope.notes.length > 0) {
  console.log("in this if");
  $scope.singleNote = $scope.notes.sort(function(a,b) { 
     return new Date(b.date_posted).getTime() - new Date(a.date_posted).getTime()
  })[0];
}