【发布时间】:2014-07-27 04:08:26
【问题描述】:
我们正在开发一款可显示员工轮班列表的应用。如果一个班次已经过去,我们希望将其从班次数组中删除,因此不将其打印到 DOM。
我们正在使用数组的delete 属性有效地删除对象。这样做,我们知道删除会将对象保留为undefined。
然而,当它在屏幕上打印时,会出现未定义(这部分是有道理的),但是当我们尝试使用函数获取它们以解决此问题时(我们将复制没有未定义的数组),我们可以' t 达到未定义。
我们如何阻止未定义?
HTML:
<ul>
<li ng-repeat="shift in CurrentUser.orderedSchedule = (schedule | orderBy:Time.getSortingDate:false)">
<p>Start time: {{Time.makeDate(shift.start)}}
{{Time.makeTime(shift.start)}}</p>
<p>end time: {{Time.makeDate(shift.end)}}
{{Time.makeTime(shift.end)}}</p>
</li>
</ul>
UserController.js:
$scope.getShifts = function(){
$scope.schedule = $scope.CurrentUser.user.shifts; //array of objects that gets printed on screen
var now = new Date();
for (var indexOfShift in $scope.schedule){ //checks each shift
var start = $scope.schedule[indexOfShift].start; //date object, the start of the shift
if(start instanceof Date){
if(parseInt(start.getTime())-parseInt(now.getTime())<0){
//if the 'future time' has already passed now
//remove the shift
alert(start+" is in the past");
delete $scope.CurrentUser.user.shifts[indexOfShift]; //deleting shift
$scope.schedule = $scope.CurrentUser.user.shifts; //trying to update that we removed it, so we can find undefined
}
}
}
for(var indexOfShift in $scope.schedule){ //looping shifts again to look for undef
console.log($scope.schedule[indexOfShift]); //this prints all of them but the undefines don't appear
if($scope.schedule[indexOfShift].start===undefined){ //we never hit this
alert("found a blank one");
}
}
};
下面是我们的用户数据与班次的样例(一个对象数组):
$scope.CurrentUser.user = [
{
'name': 'John Smith',
'shifts':[
{'start':new Date(2012, 07, 27, 4, 44),
'end': new Date(2012, 07, 27, 12, 21)
},
{'start':new Date(2014, 09, 09, 20, 02),
'end': new Date(2014, 09, 10, 7, 06)
}
]
}
];
为什么我们不能到达 undefines?他们去哪儿了?
【问题讨论】:
标签: javascript arrays angularjs object