我们正在开发一款能够显示员工轮班列表的应用。如果已经过了一个班次,我们想从班次数组中删除它,因此不会将它打印到DOM。
我们实际上是使用数组的delete
属性删除对象。这样做,我们知道删除会将对象保留为undefined
。
然而,当它在屏幕上打印时,会显示未定义的部分(这部分是有意义的),但是当我们尝试使用函数抓取它们以解决此问题时(我们将在没有取消定义的情况下复制数组),我们无法达到未定义。
我们如何阻止未定义?
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)
}
]
}
];
为什么我们无法达到未定义?他们去哪儿了?
答案 0 :(得分:1)
for(var i in arr)循环不会遍历未定义的项目。两种解决方案:
for(var i = 0; i&lt; myLength; i ++){ // 做一点事 }
答案 1 :(得分:1)
根据您的情况使用Splice。
在这种情况下删除只会将元素设置为undefined:
myArray = ['a','b','c','d']
删除myArray [0]
myArray的
结果:[未定义,“b”,“c”,“d”]
Splice实际上从数组中删除了元素:
myArray = ['a','b','c','d']
myArray.splice(0,2)
myArray的
结果:[“c”,“d”]
了解有关拼接的更多信息:Microsoft Link
来自Mizzila的例子:
var myFish =["angel", "clown", "drum", "mandarin", "surgeon"];
//removes 1 element from index 3
removed = myFish.splice(3, 1);
//myFish is ["angel", "clown", "drum", "surgeon"]
//removed is ["mandarin"]
在你的情况下使用它。
//delete $scope.CurrentUser.user.shifts[indexOfShift];
$scope.CurrentUser.user.shifts.splice(indexOfShift, 1);